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

查看:126
本文介绍了动态地将变量名称值对添加到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

我的问题是,如何添加这些名称值对/我的ipID对象配对/ tmp,这样我的结果就像

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;

它是标识属性的变量(字符串)的值,所以当你使用<$ c时$ c> 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天全站免登陆