【问题标题】:How to add objects within another array of object at alternate position?如何在另一个位置的对象数组中添加对象?
【发布时间】:2020-05-24 22:24:13
【问题描述】:

我正在开发一个反应组件。要求是在对象数组中的备用位置添加一个新对象,例如下面:

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 中做同样的事情?

【问题讨论】:

  • [...arr1, ...dummy].sort(yourSortFunction)

标签: javascript arrays node.js reactjs react-redux


【解决方案1】:

如果可以的话,我喜欢使用地图。它更容易理解和维护。

所以首先创建一个数组数组,然后用 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);

【讨论】:

    【解决方案2】:

    要修改原始数组(而不是创建新数组),可以先生成需要插入新项的索引,然后使用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);

    【讨论】:

      【解决方案3】:

      为了获得您的所需数组,您可以结合使用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)
      

      为您的 given 数组中的 last 元素添加一个 exception

      如果要修改原始数组就地,可以使用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);

      【讨论】:

      • @RobbyCornelissen,如果他想就地修改原始数组,我添加了一个解决方案。
      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多