【问题标题】:lodash - group and populate arrayslodash - 分组和填充数组
【发布时间】:2017-02-07 03:49:14
【问题描述】:

使用 lodash,我如何将具有相同生日的人的姓名分组,如下所示?

我使用嵌套的 for 循环将其写出来,但我认为在 lodash 中会有更优雅的方式来执行此操作。我没有使用太多,并试图弄清楚要使用哪个功能。

[
    { "birthdate": "1993", "name": "Ben" },
    { "birthdate": "1994", "name": "John" },
    { "birthdate": "1995", "name": "Larry" },
    { "birthdate": "1995", "name": "Nicole" },
    { "birthdate": "1996", "name": "Jane" },
    { "birthdate": "1996", "name": "Janet" },
    { "birthdate": "1996", "name": "Dora" },
]

[
    { "birthdate": "1993", "names": [ "Ben" ] }, 
    { "birthdate": "1994", "names": [ "John"] },
    { "birthdate": "1995", "names": [ "Larry", "Nicole" ] }, 
    { "birthdate": "1996", "names": [ "Jane", "Janet", "Dora" ] }        
]

【问题讨论】:

    标签: lodash


    【解决方案1】:

    您可以使用groupBy() 将集合中的每个项目按birthdate 分组。将项目分组后,您可以使用map() 迭代每个组并将它们形成一个新格式,包括birthdatenames。要从分组项中获取名称数组,可以再次使用map() 函数返回所有name 值。

    var result = _(source)
        .groupBy('birthdate')
        .map(function(items, bdate) {
          return {
            birthdate: bdate,
            names: _.map(items, 'name')
          };
        }).value();
    

    var source = [
        { "birthdate": "1993", "name": "Ben" },
        { "birthdate": "1994", "name": "John" },
        { "birthdate": "1995", "name": "Larry" },
        { "birthdate": "1995", "name": "Nicole" },
        { "birthdate": "1996", "name": "Jane" },
        { "birthdate": "1996", "name": "Janet" },
        { "birthdate": "1996", "name": "Dora" },
    ];
      
    var result = _(source)
        .groupBy('birthdate')
        .map(function(items, bdate) {
          return {
            birthdate: bdate,
            names: _.map(items, 'name')
          };
        }).value();
    
    document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"&gt;&lt;/script&gt;

    【讨论】:

    【解决方案2】:

    您可以使用reduce()find()

       let arr = [{
    	"birthdate": "1993",
    	"name": "Ben"
    },
    {
    	"birthdate": "1994",
    	"name": "John"
    },
    {
    	"birthdate": "1995",
    	"name": "Larry"
    },
    {
    	"birthdate": "1995",
    	"name": "Nicole"
    },
    {
    	"birthdate": "1996",
    	"name": "Jane"
    },
    {
    	"birthdate": "1996",
    	"name": "Janet"
    },
    {
    	"birthdate": "1996",
    	"name": "Dora"
    },
    ];
    
    const res = arr.reduce((ac, a) => {
    let temp = ac.find(x => x.birthdate === a.birthdate);
    if (!temp) ac.push({ ...a,
    	name: [a.name]
    })
    else temp.name.push(a.name)
    return ac;
    }, [])
    console.log(res);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案3】:

      您可以链接 groupBy 和 map 来实现这一点。

      _.chain(yourArray)
      .groupBy('birthdate')
      .toPairs()
      .map(s=>{
      return _.zipObject(['birthdate','names'],s)
      })
      .map(s=>{
      s.names=_.map(s.names,x=>x.name);
      return s;
      })
      .value()
      

      【讨论】:

        【解决方案4】:

        一个简单且可自定义的纯 javascript 函数,用于返回按对象所需属性分组的对象数组

        export const groupArrayBy = (arr, groupBy) => {
        
            let newArr = []
            arr.map((item) => {
                if(item[groupBy]) {
                    let finded = newArr.filter((newItem) => newItem[groupBy] === item[groupBy])
                    if(finded.length > 0) {
                        finded[0].products.push(item)
                    } else {
                        newArr.push({category: item[groupBy], products: [item]})
                    }
                }
            })
        
            return newArr
        }
        
        

        【讨论】:

          【解决方案5】:

          Lodash 简写

          var data=[
              { "birthdate": "1993", "name": "Ben" },
              { "birthdate": "1994", "name": "John" },
              { "birthdate": "1995", "name": "Larry" },
              { "birthdate": "1995", "name": "Nicole" },
              { "birthdate": "1996", "name": "Jane" },
              { "birthdate": "1996", "name": "Janet" },
              { "birthdate": "1996", "name": "Dora" },
          ];
          
          
          var list= _(data)
              .groupBy('birthdate')
              .map((items, birthdate)=> ({birthdate: birthdate,names: _.map(items, 'name')
                })).value();
                
                console.log(list)
          &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"&gt;&lt;/script&gt;

          【讨论】:

            猜你喜欢
            • 2021-10-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-16
            • 1970-01-01
            • 2014-10-03
            • 1970-01-01
            相关资源
            最近更新 更多