如何使用 ES6 函数将每个对象中具有公共 id 的对象数组组合起来
How to combine array of objects with common id in each object with ES6 functions
正在附加输入和输出格式。
`
//Input
[{"id":"146","catId":"25"},
{"id":"200","catId":"25"},
{"id":"250","catId":"55"}];
//Output expected
[{"catId":"25","topicIds":["146","200"]},
{"catId":"55","topicIds":["250"]}];
`
reduce
可用于分组问题。在这里,我按 catId
分组,它将 return 一个分组对象
{
25: {
catId: "25",
topicIds: ["146", "200"]
},
55: {
catId: "55",
topicIds: ["250"]
}
}
然后使用 Object.values
获取值数组
let a = [{"id":"146","catId":"25"},
{"id":"200","catId":"25"},
{"id":"250","catId":"55"}];
let res = Object.values(a.reduce((acc,{id,catId}) => {
acc[catId] = acc[catId] || {catId,topicIds:[]}
acc[catId].topicIds.push(id)
return acc
},{}))
console.log(res)
正在附加输入和输出格式。 `
//Input
[{"id":"146","catId":"25"},
{"id":"200","catId":"25"},
{"id":"250","catId":"55"}];
//Output expected
[{"catId":"25","topicIds":["146","200"]},
{"catId":"55","topicIds":["250"]}];
`
reduce
可用于分组问题。在这里,我按 catId
分组,它将 return 一个分组对象
{
25: {
catId: "25",
topicIds: ["146", "200"]
},
55: {
catId: "55",
topicIds: ["250"]
}
}
然后使用 Object.values
let a = [{"id":"146","catId":"25"},
{"id":"200","catId":"25"},
{"id":"250","catId":"55"}];
let res = Object.values(a.reduce((acc,{id,catId}) => {
acc[catId] = acc[catId] || {catId,topicIds:[]}
acc[catId].topicIds.push(id)
return acc
},{}))
console.log(res)