我有这个数组索引,我想要修改的数组如下:索引0-1是第一个,2 -3是第二个,4-5是第三个,依此类推
结果数组:[first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]
如何修改这种类型的数组?
发布于 2020-12-22 15:56:18
您期望的结果不是有效的数组。
[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;
}, []);发布于 2020-12-22 14:55:16
您可以使用array.prototype.map。此示例返回每个对象的id值乘以它在数组中存在的数字。
let arr = [{id:1},{id:2},{id:3},{id:5},{id:5}];
arr.map(function(item,index) {
return item.id * index;
})试试看!
https://stackoverflow.com/questions/65404259
复制相似问题