簡體   English   中英

如何在另一個位置的對象數組中添加對象?

[英]How to add objects within another array of object at alternate position?

我正在研究一個反應組件。 要求是在對象數組中的備用位置添加一個新對象,例如:

arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}]

預期輸出:

arr1 = [{test: 1},{dummy:1},{test: 2},{dummy:1},{test: 3},{dummy:1},{test: 4}]

有沒有辦法在es6中做同樣的事情?

為了獲得所需的數組,您可以將concat方法與reduce結合使用。

 var array = [{test: 1},{test: 2},{test: 3},{test: 4}]; var result = array.reduce((res, item) => res.concat(item, {dummy: 1}), []).slice(0, -1); console.log(result);

由於這會在數組中的每個元素之后添加{dummy: 1}對象,因此只需使用

.slice(0, -1)

給定數組中的最后一個元素添加一個例外

如果要就地修改原始數組,可以使用splice方法。

 var array = [{test: 1},{test: 2},{test: 3},{test: 4}]; for(i = 0;i < array.length - 1; i = i + 2){ array.splice(i + 1, 0, {dummy: 1}); } console.log(array);

如果可以,我喜歡使用地圖。 更容易理解和維護。

因此,首先創建一個數組數組,然后將其扁平化為單個數組。

 let arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}] arr1 = arr1.map(item=>[item,{dummy:1}]).flat().slice(0, -1) console.log(arr1);

要修改原始數組(而不是創建新數組),您可以先生成需要插入新項的索引,然后使用Array.prototype.splice()

 const a = [{test: 1}, {test: 2}, {test: 3}, {test: 4}]; Array.from({length: a.length - 1}, (_, i) => i * 2 + 1) .forEach(i => a.splice(i, 0, {dummy: 1})); console.log(a);

暫無
暫無

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

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