gpt4 book ai didi

javascript - 使用 JavaScript ES6 迭代器转换数组

转载 作者:行者123 更新时间:2023-12-03 00:33:07 31 4
gpt4 key购买 nike

如何使用 javascript es6 迭代器函数将员工数组变量转换为部门数组变量?我正在寻找有效的解决方案。

来自:

var employees = [
{ name: 'John', department: 'Digital Experience' },
{ name: 'Doe', department: 'Digital Transformation' },
{ name: 'Symon', department: 'Digital Planning' },
{ name: 'Joey', department: 'Digital Experience' },
{ name: 'Abul', department: 'Digital Experience' },
{ name: 'Smith', department: 'Digital Experience' },
{ name: 'Ajad', department: 'Digital Transformation' },
{ name: 'Rahim', department: 'Digital Transformation' },
{ name: 'Luke', department: 'Digital Planning' },
];

致:

var departments = [
{
department: 'Digital Experience',
employeeNames: ['Johm', 'Joey', 'Abul', 'Smith']
},
{
department: 'Digital Transformation',
employeeNames: ['Doe', 'Ajad', 'Rahim']
},
{
department: 'Digital Planning',
employeeNames: ['Symon', 'Luke']
}
]

最佳答案

我确信还有其他方法,但这看起来相当短。

var e = [
{ name: 'John', department: 'Digital Experience' },
{ name: 'Doe', department: 'Digital Transformation' },
{ name: 'Symon', department: 'Digital Planning' },
{ name: 'Joey', department: 'Digital Experience' },
{ name: 'Abul', department: 'Digital Experience' },
{ name: 'Smith', department: 'Digital Experience' },
{ name: 'Ajad', department: 'Digital Transformation' },
{ name: 'Rahim', department: 'Digital Transformation' },
{ name: 'Luke', department: 'Digital Planning' },
];

const departments = [...new Set(e.map(x => x.department))].map(y => {
return {
department: y,
employeeNames: e.filter(z => z.department === y).map(w => w.name)
}
})

console.log(departments)

关于javascript - 使用 JavaScript ES6 迭代器转换数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53774685/

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