Javascript:在不覆盖键的情况下重构对象数组
Javascript: Refactor array of objects without overwriting keys
我有一个对象数组,我想重构它们(制作一个不同的结构)..
现有数组:
[ 0: { category: 100 },
1: { category: 101 },
2: { category: 102 },
3: { tag: 200 },
4: { tag: 201 },
5: { tag: 202 },
6: { year: 300 },
7: { year: 301 },
8: { year: 302 }
]
想要数组:
[ 0: { category: [ 100, 101, 102 ] },
1: { tag: [ 200, 201, 202 ] },
2: { year: [ 300, 301, 302 ] }
]
非常感谢任何帮助。欢迎使用 ES6 语法。
使用Array.prototype.reduce
let input = [{ category: 100 },
{ category: 101 },
{ category: 102 },
{ tag: 200 },
{ tag: 201 },
{ tag: 202 },
{ year: 300 },
{ year: 301 },
{ year: 302 }
];
let output = input.reduce((acc, curr) => {
let key = Object.keys(curr)[0];
acc[key] = acc[key] ? [curr[key], ...acc[key]] : [curr[key]];
return acc;
}, {});
console.log(output)
我有一个对象数组,我想重构它们(制作一个不同的结构)..
现有数组:
[ 0: { category: 100 },
1: { category: 101 },
2: { category: 102 },
3: { tag: 200 },
4: { tag: 201 },
5: { tag: 202 },
6: { year: 300 },
7: { year: 301 },
8: { year: 302 }
]
想要数组:
[ 0: { category: [ 100, 101, 102 ] },
1: { tag: [ 200, 201, 202 ] },
2: { year: [ 300, 301, 302 ] }
]
非常感谢任何帮助。欢迎使用 ES6 语法。
使用Array.prototype.reduce
let input = [{ category: 100 },
{ category: 101 },
{ category: 102 },
{ tag: 200 },
{ tag: 201 },
{ tag: 202 },
{ year: 300 },
{ year: 301 },
{ year: 302 }
];
let output = input.reduce((acc, curr) => {
let key = Object.keys(curr)[0];
acc[key] = acc[key] ? [curr[key], ...acc[key]] : [curr[key]];
return acc;
}, {});
console.log(output)