Javascript 将变量名值对动态添加到 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4071499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:21:43  来源:igfitidea点击:

Dynamically Add Variable Name Value Pairs to JSON Object

javascriptobjectobject-literal

提问by Mike

I have a json object full of ips like

我有一个充满 ips 的 json 对象,例如

var ips = {}

I then add ip objects to this object like so

然后我像这样将 ip 对象添加到这个对象

ips[ipID] = {}

I then need to add dynamic/variable name value pairs to each ip so I am using code like this

然后我需要向每个 ip 添加动态/变量名称值对,所以我使用这样的代码

var name; var value; var temp = {};
tmp[name] = value

My question is, how can I add these name value pairs/ tmp to my ipID objects so that my outcome turns out like

我的问题是,如何将这些名称值对/ tmp 添加到我的 ipID 对象中,以便我的结果像

ipID = { name : value, anotherName : anotherValue }

回答by Guffa

That's not JSON. It's just Javascript objects, and has nothing at all to do with JSON.

那不是 JSON。它只是 Javascript 对象,与 JSON 毫无关系。

You can use brackets to set the properties dynamically. Example:

您可以使用括号动态设置属性。例子:

var obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;

This gives exactly the same as creating the object with an object literal like this:

这与使用这样的对象文字创建对象完全相同:

var obj = { name : value, anotherName : anotherValue };

If you have already added the object to the ipscollection, you use one pair of brackets to access the object in the collection, and another pair to access the propery in the object:

如果您已经将对象添加到ips集合中,则使用一对括号访问集合中的对象,使用另一对括号访问对象中的属性:

ips[ipId] = {};
ips[ipId]['name'] = value;
ips[ipId]['anotherName'] = anotherValue;

Notice similarity with the code above, but that you are just using ips[ipId]instead of obj.

请注意与上面的代码的相似之处,但您只是使用ips[ipId]而不是obj.

You can also get a reference to the object back from the collection, and use that to access the object while it remains in the collection:

您还可以从集合中获取对对象的引用,并使用它来访问保留在集合中的对象:

ips[ipId] = {};
var obj = ips[ipId];
obj['name'] = value;
obj['anotherName'] = anotherValue;

You can use string variables to specify the names of the properties:

您可以使用字符串变量来指定属性的名称:

var name = 'name';
obj[name] = value;
name = 'anotherName';
obj[name] = anotherValue;

It's value of the variable (the string) that identifies the property, so while you use obj[name]for both properties in the code above, it's the string in the variable at the moment that you access it that determines what property will be accessed.

它是标识属性的变量(字符串)的值,因此当您obj[name]在上面的代码中使用这两个属性时,正是访问它时变量中的字符串决定了将访问哪个属性。

回答by Dylan Hogg

With ECMAScript 6 there is a better way.

ECMAScript 6 有更好的方法。

You can use computed property namesin object property definitions, for example:

您可以在对象属性定义中使用计算属性名称,例如:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

这等效于以下内容,其中您有属性名称的变量。

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

回答by Max

when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

使用 javascript 对象时,您也可以只使用“点符号”来添加一个项目,(JSLint 更喜欢

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

这是在 Chrome 控制台中测试的屏幕截图

screenshot

截屏

回答by orangepips

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

我假设“ips”中的每个条目都可以有多个名称值对 - 所以它是嵌套的。您可以这样实现此数据结构:

var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

回答by Atif Hussain

in Javascript.

在 JavaScript 中。

    var myObject = { "name" : "john" };
    // { "name" : "john" };
    myObject.gender = "male";
    // { "name" : "john", "gender":"male"};

回答by Hamzeen Hameem

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

如果我对您的初始 JSON 的理解是正确的,那么这些解决方案中的任何一个都可以帮助您遍历所有 ip id 并为每个 ip id 分配一个新对象。

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

确认:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

上面的说法吐槽:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

回答by user4953229

From what the other answers have proposed, I believe this might help:

根据其他答案的建议,我相信这可能会有所帮助:

var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:

但是,这没有经过测试,只是基于以下不断重复的假设:

object["string"] = value;
//object = {string: value}

回答by Penny Liu

You can achieve this using Lodash_.assignfunction.

您可以使用Lodash_.assign函数来实现这一点

var ipID = {};
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});
console.log(ipID);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>