a8h*_*hok 2 javascript arrays object
我有一个对象数组,我必须按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}
]
Run Code Online (Sandbox Code Playgroud)
预期结果应该是:
{
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}
]
}
Run Code Online (Sandbox Code Playgroud)
这里有一种使用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);
Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Run Code Online (Sandbox Code Playgroud)
前面的示例将对具有相同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);
Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5450 次 |
最近记录: |