【发布时间】:2017-09-05 17:35:26
【问题描述】:
我有一个对象数组,如下所示:
data = [
{
title: 'John Doe',
departments: [
{ name: 'Marketing', slug: 'marketing'},
{ name: 'Sales', slug: 'sales'},
{ name: 'Administration', slug: 'administration'},
]
},
{
title: 'John Doe Junior',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Sales', slug: 'sales'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
如何遍历每个对象的部门数组并创建新数组,让员工按部门排序,以便最终结果如下:
operations = [
{
title: 'John Doe Junior',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Sales', slug: 'sales'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
marketing = [
{
title: 'John Doe',
departments: [
{ name: 'Marketing', slug: 'marketing'},
{ name: 'Sales', slug: 'sales'},
{ name: 'Administration', slug: 'administration'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
动态创建这种数组的方法是什么?
更新
我尝试使用答案中的建议提出一个解决方案,我将在其中动态创建一个包含部门对象的数组,该数组将包含一组员工:
const isInDepartment = departmentToCheck => employer => employer.departments.find(department => department.slug == departmentToCheck);
var departments = [];
function check(departments, name) {
return departments.some(object => name === object.department);
}
employees.forEach((employee) => {
employee.departments.forEach((department) => {
let found = check(departments, department.slug);
if (!found) {
departments.push({ department: department.slug });
}
});
});
departments.forEach((department) => {
// push an array of employees to each department
//employees.filter(isInDepartment(department));
});
但是,我不知道如何将员工数组推送到最后循环的数组中的对象? 这是fiddle。
【问题讨论】:
-
@T.J.Crowder 我已经编辑了问题并修正了语法
-
那是什么类型的语法?您可以使用 console.log 在 json 中输出一个干净的变量表示,如下所示:console.log(JSON.stringify(someVar));
-
我再次编辑了这个问题,之前我只是从控制台用 chrome 复制它,对此我深表歉意
-
太棒了!那么你被困在哪里了?你的研究结果是什么?另请参阅:stackoverflow.com/questions/9329446/… 除非我遗漏了什么,否则这只是嵌套循环(您最喜欢的口味来自该答案中提供的菜单)。 (不是我的 dv)
标签: javascript arrays sorting ecmascript-6