将元素添加到空json数组并删除它们

时间:2022-05-24 15:42:21

I have created an empty json object having an array itemlist(which further contains itemid and title of an item) by this:

我已经创建了一个空的json对象,它有一个数组项目列表(它还包含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:

其次,title和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函数可以用于此,但是如何找到该元素的索引?

1 个解决方案

#1


6  

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 splice will mess up the array indexes

请注意,您需要向后移动,否则拼接会使数组索引陷入混乱

#1


6  

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 splice will mess up the array indexes

请注意,您需要向后移动,否则拼接会使数组索引陷入混乱