gpt4 book ai didi

javascript - 在 Javascript 中从另一个数组中创建一个对象数组,对重复项进行分组

转载 作者:行者123 更新时间:2023-12-03 08:10:17 24 4
gpt4 key购买 nike

我需要根据对象的一个​​属性将对象数组(来自数据库)重新组织成不同的组。为了更清楚地说明这一点,我们来看以下示例:

ORM(Sequelize)返回以下数组对象:

[
{
id: 182,
employeeId: 'a',
skillId: 207,
score: 3,
},
{
id: 512,
employeeId: 'a',
skillId: 212,
score: 4,
},
{
id: 908,
employeeId: 'b',
skillId: 134,
score: 2,
},
{
id: 876,
employeeId: 'c',
skillId: 212,
score: 3,
},
]

我需要重新对按employeeId 对条目进行分组的对象进行分类。像这样:

[
{
employeeId: 'a',
skills:
[
{ skillId: 203, score: 3},
{ skillId: 212, score: 4}
]
},
{
employeeId: 'b',
skills:
[
{ skillId: 134, score: 2}
]
},
{
employeeId: 'c',
skills:
[
{ skillId: 212, score: 3}
]
}
]

一开始看起来并不难,但我遇到了障碍,我已经尝试使用reduce、forEarch和map,但我只需要制作一个employeeIds数组,无法真正将技能数组包含在其中数组的每个对象。

如有任何帮助,我们将不胜感激。

最佳答案

const result = [
{
id: 182,
employeeId: 'a',
skillId: 207,
score: 3,
},
{
id: 512,
employeeId: 'a',
skillId: 212,
score: 4,
},
{
id: 908,
employeeId: 'b',
skillId: 134,
score: 2,
},
{
id: 876,
employeeId: 'c',
skillId: 212,
score: 3,
},
]



const tempObj = result.reduce((acc, curr) => {
if (curr.employeeId in acc) {
acc[curr.employeeId].push({
skillId: curr.skillId,
score: curr.score
})
} else {
acc[curr.employeeId] = [{
skillId: curr.skillId,
score: curr.score
}]
}
return acc
}, {})

const reorganized = Object.keys(tempObj).map(key => ({
employeeId: key,
skills: tempObj[key]
}))

console.log(JSON.stringify(reorganized, null, 2))

关于javascript - 在 Javascript 中从另一个数组中创建一个对象数组,对重复项进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71039813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com