使用splice将一个对象添加到对象数组中

12

我有一个对象数组,它看起来像这样:

event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];

我该如何向这个数组中添加元素?

我想到了以下方法:

event_id.splice(1,0,{"0":"e5"});

谢谢。


这个问题已经在这里回答过了:https://dev59.com/_nRB5IYBdhLWcg3wkH5N#12189963 - Luis Perez
5个回答

12

如果你想向数组末尾添加一个值,那么使用 push(newObj) 函数是最容易的方法,尽管 splice(...) 也可以实现(只是有点棘手)。

var event_id = [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}];
event_id.push({"0":"e5"});
//event_id.splice(event_id.length, 0, {"0":"e5"}); // Same as above.
//event_id[event_id.length] = {"0":"e5"}; // Also the same.
event_id; // => [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}, {"0":"e5"}]; 

参见优秀的Array对象的MDN文档,该文档对数组可用的方法和属性提供了很好的参考。

[编辑] 要在数组中间插入某个元素,您肯定会想使用splice(index, numToDelete, el1, el2, ..., eln)方法,该方法可以处理在任何位置删除并插入任意元素:

var a  = ['a', 'b', 'e'];
a.splice( 2,   // At index 2 (where the 'e' is),
          0,   // delete zero elements,
         'c',  // and insert the element 'c',
         'd'); // and the element 'd'.
a; // => ['a', 'b', 'c', 'd', 'e']

我想在数组中间添加对象。 - user823527

11

由于我想将对象添加到数组的中间位置,所以最终采用了以下解决方案:

var add_object = {"0": "e5"};
event_id.splice(n, 0, add_object); // n is declared and is the index where to add the object

删除值为 'e5' 的对象怎么样? - Krishna Prasad Varma

3

使用展开运算符的ES6解决方案:

event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];
event_id = [...event_id,{"0":"e5"}]

如果您不想改变event_id,

newEventId = [...event_id,{"0":"e5"}]

更新: 要在特定索引、对象键或对象值之后插入对象,你可以:

const arr = [{a:1},{b:2},{c:3},{d:4}]

arr.reduce((list,obj,index)=>index===1 ? [...list,obj,{g:10}] : [...list,obj], [])
arr.reduce((list,obj)=>Object.keys(obj)[0]==='b' ? [...list,obj,{g:10}] : [...list,obj], [])
arr.reduce((list,obj)=>Object.values(obj)[0]===2 ? [...list,obj,{g:10}] : [...list,obj], [])

// output:  [ { a: 1 }, { b: 2 }, { g: 10 }, { c: 3 }, { d: 4 } ]

你不能使用此方法将对象添加到对象数组的中间位置。只有开头和结尾会起作用。 - RBG
是的,你是对的...我刚刚更新了答案,添加了在数组中间插入对象的部分。 - AndreasT

0
event_id.push({"something", "else"});

尝试使用.push(...) ^


问题陈述为:event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];,这是一个数组。 - Naftali

0

你通常可以使用以下方法:

event_id[event_id.length] = {"0":"e5"};

或者(稍微慢一些的)

event_id.push({"0":"e5"});

如果你想把一个元素插入到数组的中间而不是总是在末尾,那么我们就需要想出一些更有创意的方法。

希望能帮到你,

ise


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接