将变量名值对动态添加到 JSON 对象 [英] Dynamically Add Variable Name Value Pairs to JSON Object

查看:24
本文介绍了将变量名值对动态添加到 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a json object full of ips like

var ips = {}

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

I then add ip objects to this object like so

ips[ipID] = {}

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

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

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

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

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

ipID = { name : value, anotherName : anotherValue }

推荐答案

那不是 JSON.它只是 Javascript 对象,与 JSON 完全没有关系.

That's not JSON. It's just Javascript objects, and has nothing at all to do with 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 };

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

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

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

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

Notice similarity with the code above, but that you are just using ips[ipId] instead of 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;

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

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.

这篇关于将变量名值对动态添加到 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆