[英]How to add objects within another array of object at alternate position?
I am working on a react component.我正在研究一个反应组件。 Requirement is to add a new object at alternate position within array of object eg below:
要求是在对象数组中的备用位置添加一个新对象,例如:
arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}]
expected output:预期输出:
arr1 = [{test: 1},{dummy:1},{test: 2},{dummy:1},{test: 3},{dummy:1},{test: 4}]
is there a way to do the same in es6?有没有办法在es6中做同样的事情?
For getting your desired array, you could make of use the concat
method in combination with reduce
.为了获得所需的数组,您可以将
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);
Since this adds {dummy: 1}
object after each element from your array, just use由于这会在数组中的每个元素之后添加
{dummy: 1}
对象,因此只需使用
.slice(0, -1)
to add one exception for the last element from your given array.为给定数组中的最后一个元素添加一个例外。
If you want to modify the original array inplace , you could use splice
method.如果要就地修改原始数组,可以使用
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);
I like to use map if I can.如果可以,我喜欢使用地图。 It is easier to understand and maintain.
更容易理解和维护。
So first create an array of array and then flatten it a single array with flat.因此,首先创建一个数组数组,然后将其扁平化为单个数组。
let arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}] arr1 = arr1.map(item=>[item,{dummy:1}]).flat().slice(0, -1) console.log(arr1);
To modify the original array (instead of creating an new one), you can first generate the indexes at which the new items need to be inserted, and then use Array.prototype.splice()
:要修改原始数组(而不是创建新数组),您可以先生成需要插入新项的索引,然后使用
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.