我无法弄清楚如何在不迭代数组三次的情况下做到这一点。
我希望转换一系列看起来像这样的工作清单:
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'
},
],
};
_map
这是我最好的选择吗?有没有更有说服力的方法呢?
答案 0 :(得分:4)
您可以使用array#reduce
根据department
对作业进行分组。
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 = jobs.reduce((r,job) => {
r[job.department] = r[job.department] || [];
r[job.department].push(job);
return r;
},{});
console.log(deps);

您可以使用_.groupBy
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 = _.groupBy(jobs, 'department');
console.log(deps);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;