如何使用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']
}
]
答案 0 :(得分:1)
我敢肯定还有其他方法,但这似乎很短。
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)