首页 > 解决方案 > 我们如何将 javascript 数组修改为数组对象?

问题描述

我有这个数组arr = [{id:1},{id:2},{id:3},{id:5},{id:5}] 我想修改数组,比如索引 0 - 1 是第一个,2 -3 是第二个,4 - 5 是第三个等等

结果数组: [first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]

如何修改这种类型的数组?

标签: javascript

解决方案


您期望的结果不是有效的数组。

[first: [{},{}]]

它应该是这样的数组

[[{},{}],[{},{}]]

或一个物体

{"first":[{},{}],"second":[{},{}]}

下面的代码将您的输入转换为一个数组,如果您正在寻找一个对象,则可以通过一些小的修改轻松地将其修改为一个对象。

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
  if (index % 2 == 0) {
    acc.push([current]);
  } else {
    acc[Math.floor(index / 2)].push(current);
  }
  return acc;
}, []);


推荐阅读