动态添加到 Javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4071252/
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
Dynamically Add to Javascript Object
提问by Mike
I have a Javascript object that looks like this.
我有一个看起来像这样的 Javascript 对象。
ips[ipID] = {}
ips[ipID] = {}
So I end up with a bunch of ips that need to store information that will look like
所以我最终得到了一堆需要存储信息的ips,看起来像
ipID { name : 'val', anotherName : 'anotherVal' }
ipID { name : 'val', anotherName : 'anotherVal' }
My question is, how do I dynamically add these names and values?
我的问题是,如何动态添加这些名称和值?
回答by mathisonian
I believe this is the easiest thing to do if your names are dynamic:
如果你的名字是动态的,我相信这是最简单的事情:
var myobj = {};
var newFieldName = 'my new field name';
var newFieldValue = 'my new field value';
myobj[newFieldName] = newFieldValue;
回答by Jakub Konecki
var ipID = {};
ipID.name = 'val';
ipID.anotherName = 'anotherVal';
回答by OlliM
If you would like to use the great underscore library (a swiss army knife for js developers), you could use the extend method http://documentcloud.github.com/underscore/#extend.
如果你想使用伟大的下划线库(js 开发者的瑞士军刀),你可以使用扩展方法http://documentcloud.github.com/underscore/#extend。
So for example
所以例如
var tmp = { name: "asdf", val: "value" };
_(ips[ipID]).extend(tmp);
Hope this is clear, it would be easier to help if you had a more precise question.
希望这很清楚,如果您有更精确的问题,会更容易提供帮助。
回答by Muhammad Fahad
Solution For JSONObject:
JSON对象的解决方案:
By default:
默认情况下:
array=[];
object={};
JSON Code:
JSON 代码:
var People= {};
Json.People[key]="value";
JSON Result:
JSON 结果:
{People:
{
key: "value"
}
}