JQuery 和 JSON - 添加元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2921498/
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
JQuery and JSON - Add element
提问by Villager
I have a JSON variable defined as:
我有一个 JSON 变量定义为:
var myCollection = {
"data": [
{ "name":"Joe", "id":"1" },
{ "name":"Bill", "id":"2" },
{ "name":"Dave", "id":"3" }
]
};
I have a JavaScript function that is responsible for adding items to the data element in myCollection. However, I'm not sure how to add a name/id pair to the collection via JavaScript. Can someone show me how to add to a JSON collection via JavaScript?
我有一个 JavaScript 函数,负责向 myCollection 中的数据元素添加项目。但是,我不确定如何通过 JavaScript 将名称/ID 对添加到集合中。有人可以告诉我如何通过 JavaScript 添加到 JSON 集合吗?
Thank you!
谢谢!
回答by Philippe Leybaert
You can simply call the push method on the "data" array:
您可以简单地在“数据”数组上调用 push 方法:
myCollection.data.push( { "name":"Jim", "id":"4" } );