【问题标题】:Use Lodash map to reorganize list into sorted keys by value使用 Lodash map 将列表按值重新组织为排序的键
【发布时间】:2018-02-13 18:03:26
【问题描述】:

如果不对数组进行三次迭代,我无法弄清楚如何做到这一点。

我希望转换一组如下所示的职位列表:

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 是我最好的选择吗?有没有更雄辩的方式来做到这一点?

【问题讨论】:

  • 看起来像groupBy
  • 你的结果应该是一个对象。
  • 如果是我,我会使用Array.reduce
  • @HassanImam 你是对的,我正在寻找一个对象。问题已更新。

标签: javascript ecmascript-6 lodash


【解决方案1】:

您可以使用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>

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2019-12-26
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多