【发布时间】:2020-10-05 08:27:15
【问题描述】:
我有一个需要转换为新对象的对象数组。一些值作为键和值数组。
const data = [
{
type: 'user',
id: 1
},
{
type: 'user',
id: 2
},
{
type: 'group',
id: 1
},
{
type: 'group',
id: 2
},
{
type: 'user',
id: 3
},
{
type: 'user',
id: 4
}
]
想要的结果是
const result = {
user: [1, 2, 3, 4],
group: [1, 2]
}
我尝试过使用 reduced,但这不是我所期望的。
const result = data.reduce((acc, { type, ...obj }) => {
acc[type] = data.map(item => item.id)
return acc;
}, {})
result = { user: [ 1, 2, 1, 2, 3, 4 ], group: [ 1, 2, 1, 2, 3, 4 ] }
【问题讨论】:
标签: javascript arrays algorithm object javascript-objects