簡體   English   中英

使用 splice 將對象添加到對象數組

[英]Adding an object to an array of objects with splice

我有一個看起來像這樣的對象數組:

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 文檔,以獲得有關數組上可用的方法和屬性的良好參考。

[編輯]要在數組的中間插入一些東西,那么你肯定要使用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"}]

更新:分別在特定索引或對象鍵或對象值后插入對象,您可以:

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"});

但是,如果您想將一個元素插入到數組的中間而不總是在最后,那么我們將不得不想出一些更有創意的東西。

希望能幫助到你,

伊勢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM