我有一个对象数组,我必须按 index
属性上的重复值拆分它。对于像下一个这样的对象示例数组:
[
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3}
]
预期的结果应该是:
{
0: [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3}
],
1: [
{index: 1, value: 3},
{index: 1, value: 3}
],
2: [
{index: 2, value: 3},
{index: 2, value: 3}
]
}
最佳答案
这里有一个使用 reduce() 的解决方案和 Object.assign() :
const input = [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3},
{index: 0, value: 3}
];
let obj = input.reduce((res, curr) =>
{
if (res[curr.index])
res[curr.index].push(curr);
else
Object.assign(res, {[curr.index]: [curr]});
return res;
}, {});
console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
前面的示例将对具有相同 index
属性的所有对象进行分组。但是,如果您希望通过具有相同 indexes
的条纹来分隔对象,您可以这样做:
const input = [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 2, value: 3},
{index: 2, value: 3}
];
let obj = input.reduce((res, curr) =>
{
if (curr.index === res.last)
{
res.r[res.idx - 1].push(curr);
return res;
}
Object.assign(res.r, {[res.idx]: [curr]});
res.last = curr.index;
res.idx++;
return res;
}, {r: {}, idx: 0, last: null});
console.log(obj.r);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 如何按重复值拆分数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54270491/