将元素添加到空的 json 数组并删除它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11132320/
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
adding elements to empty json array and removing them
提问by Vatsal Juneja
I have created an empty json object having an array itemlist(which further contains itemid and title of an item) by this:
我创建了一个空的 json 对象,它有一个数组 itemlist(它进一步包含 itemid 和一个项目的标题):
var jsonObj = {};
jsonObj.itemlist=[];
jsonObj.itemlist.push({});
Firstly, have i done the declaration correctly?
首先,我是否正确完成了声明?
Secondly, the title and itemid are generated dynamically so i need to add them to the itemlist array. I tried this but it keeps only one array element:
其次,标题和 itemid 是动态生成的,所以我需要将它们添加到 itemlist 数组中。我试过了,但它只保留了一个数组元素:
jsonObj.itemlist['title']=gentitle;
jsonObj.itemlist['itemid']=genitemid;
How can i add multiple elements (not all at once) if i have an empty array of itemlists?
如果我有一个空的项目列表数组,我如何添加多个元素(不是一次全部)?
Also, i also need to remove a particular array element based on the title of the element. How can that be done? I think the splice and delete function can be used for this, but how can i find the index of that element?
此外,我还需要根据元素的标题删除特定的数组元素。那怎么办呢?我认为 splice 和 delete 功能可以用于此,但我如何找到该元素的索引?
回答by xvatar
since you already pushed a empty object into the array, you need to modify that object:
由于您已经将一个空对象推送到数组中,因此您需要修改该对象:
jsonObj.itemlist[0]['title']=gentitle;
jsonObj.itemlist[0]['itemid']=genitemid;
To add more objects, you can do the same thing: push in an empty object, then modify that object. Or, you can create an object, modify it, then push it into the list.
要添加更多对象,您可以执行相同的操作:推入一个空对象,然后修改该对象。或者,您可以创建一个对象,对其进行修改,然后将其推送到列表中。
var new_obj = {'title':gentitle, 'itemid':genitemid};
jsonObj.itemlist.push( new_obj );
To delete objects with certain attribute value:
删除具有特定属性值的对象:
for (var i = jsonObj.itemlist.length-1; i >= 0; i--)
if(jsonObj.itemlist[i]['title'] == "to-be-removed")
jsonObj.itemlist.splice(i,1);
Note that you need to go backward, otherwise the splicewill mess up the array indexes
请注意,您需要向后退,否则splice会弄乱数组索引

