繁体   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