使用Lodash映射按值将列表重组为已排序的键

时间:2018-02-13 18:03:26

标签: javascript ecmascript-6 lodash

我无法弄清楚如何在不迭代数组三次的情况下做到这一点。

我希望转换一系列看起来像这样的工作清单:

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这是我最好的选择吗?有没有更有说服力的方法呢?

1 个答案:

答案 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;
&#13;
&#13;