【问题标题】:Grouping objects with lodash or ES5使用 lodash 或 ES5 对对象进行分组
【发布时间】:2018-01-09 08:11:04
【问题描述】:

我是 javascript noobie,我开始使用库 lodash,但遇到了一些问题。有人能帮我吗? :/

输入:

var a = [{group: 'A', title: 'test1', value: 'test2'},
         {group: 'A', title: 'test2', value: 'test3'},
         {group: 'B', title: 'test3', value: 'test4'},
         {group: 'B', title: 'test1', value: 'test2'},]

输出:

var a = {A: [
         { title: 'test1', value: 'test2'},
         { title: 'test2', value: 'test3'}
        ],
         B: [
         { title: 'test1', value: 'test2'},
         { title: 'test2', value: 'test3'}
        ],}

【问题讨论】:

    标签: arrays json node.js typescript lodash


    【解决方案1】:

    您可以使用_.groupBy() 进行分组,然后在每个组上使用_.mapValues(),通过使用_.omit() 将对象映射到新对象来从对象中删除group 属性。

    const a = [{group: 'A', title: 'test1', value: 'test2'},
             {group: 'A', title: 'test2', value: 'test3'},
             {group: 'B', title: 'test3', value: 'test4'},
             {group: 'B', title: 'test1', value: 'test2'}
           ];
           
    const result = _(a)
      .groupBy('group') // group by the group prop
      .mapValues((group) => group.map((o) => _.omit(o, 'group'))) // remove the group prop from each item
      .value();
      
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    【讨论】:

      【解决方案2】:

      group by 的 lodash 文档非常明确,您可以在 here 找到它。

      在你的情况下,它看起来像这样。

      _.groupBy(a, 'group')
      

      您也可以使用 reduce 功能自己轻松完成。它看起来像这样:

      let groups = a.reduce((grouping, currentItem) => {
          if (!grouping[currentItem.group]) {
              grouping[currentItem.group] = []
          }
          grouping[currentItem.group].push(currentItem);
          return grouping;
      }, {});
      

      可以在here 找到一个工作示例。

      在这两种情况下,结果都是以组作为属性名称的对象。

      {
        "A": [{
          "group": "A",
          "title": "test1",
          "value": "test2"
        }, {
          "group": "A",
          "title": "test2",
          "value": "test3"
        }],
        "B": [{
          "group": "B",
          "title": "test3",
          "value": "test4"
        }, {
          "group": "B",
          "title": "test1",
          "value": "test2"
        }]
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 2023-01-25
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        • 2018-08-28
        相关资源
        最近更新 更多