将对象添加到具有拼接的对象阵列中

Adding an object to an array of objects with splice

本文关键字:对象 阵列 拼接 添加      更新时间:2023-09-26

我有一个对象数组,如下所示:

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

如何将元素添加到该数组中?

我想到了

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

谢谢。

如果您只想在数组的末尾添加一个值,那么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文档,以获得阵列上可用的方法和属性的良好参考。

[Edit]要在数组的中间插入一些东西,您肯定需要使用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']

由于我想在数组的中间添加对象,所以我以这个解决方案结束:

var add_object = {"0": "e5"};
event_id.splice(n, 0, add_object); // n is declared and is the index where to add the object
带有排列运算符的ES6解决方案:
event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];
event_id = [...event_id,{"0":"e5"}]

或者如果您不想更改event_id

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

UPDATE:要分别在特定索引或对象键或对象值后插入对象,您可以:

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 } ]
event_id.push({"something", "else"});

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

通常可以使用:

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

或者(稍微慢一点)

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

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

希望有帮助,

ise