Javascript 使用Lodash映射将列表重新组织为按值排序的键
我很抱歉,如果不在数组上迭代三次,我就不知道如何执行此操作 我希望转换一系列工作列表,如下所示:Javascript 使用Lodash映射将列表重新组织为按值排序的键,javascript,ecmascript-6,lodash,Javascript,Ecmascript 6,Lodash,我很抱歉,如果不在数组上迭代三次,我就不知道如何执行此操作 我希望转换一系列工作列表,如下所示: const jobs = [ { title: 'Manager', department: 'Retail', location: 'New York' }, { title: 'Customer Service Rep', department: 'Corporate', location: 'Washington D.C.' },
const jobs = [
{
title: 'Manager',
department: 'Retail',
location: 'New York'
},
{
title: 'Customer Service Rep',
department: 'Corporate',
location: 'Washington D.C.'
},
{
title: 'Clerk',
department: 'Retail',
location: 'New York'
},
...
];
进入具有关联作业的唯一部门的对象:
const deps = {
'Corporate': [
{
title: 'Customer Service Rep',
department: 'Corporate',
location: 'Washington D.C.'
},
],
'Retail': [
{
title: 'Manager',
department: 'Retail',
location: 'New York'
},
{
title: 'Clerk',
department: 'Retail',
location: 'New York'
},
],
};
\u map
是我在这里的最佳选择吗?有没有更雄辩的方法呢?您可以使用数组#reduce
根据部门对作业进行分组
const jobs=[{title:'Manager',department:'Retail',location:'New York'},{title:'Customer Service Rep',department:'Corporate',location:'Washington D.C.},{title:'Clerk',department:'Retail location:'New York'}],
deps=作业。减少((r,作业)=>{
r[job.department]=r[job.department]| |[];
r[job.department].push(作业);
返回r;
},{});
控制台日志(deps)
您可以使用数组#reduce
根据部门对作业进行分组
const jobs=[{title:'Manager',department:'Retail',location:'New York'},{title:'Customer Service Rep',department:'Corporate',location:'Washington D.C.},{title:'Clerk',department:'Retail location:'New York'}],
deps=作业。减少((r,作业)=>{
r[job.department]=r[job.department]| |[];
r[job.department].push(作业);
返回r;
},{});
控制台日志(deps)
看起来像groupBy
你的结果应该是一个对象。如果是我,我就用它。@hassaniam你说得对,我在找一个对象。问题已更新。看起来groupBy
你的结果应该是一个对象。如果是我,我就用它。@Hassaniam你说得对,我在找一个对象。问题已更新。