Search code examples
typescriptgroup-bylodash

Typescript lodash Groupby nested array


Can some one help me on how to use lodash groupby to achieve the below input to my desired output? I have tried lodash groupby methods as discussed in other links but could not achieve the output I expected. Input:

inputList: dataMaster[] = [
  {
    "isSelected": true,
    "GroupKey": "G1",
    "GroupName": "Group1",
    "Key": "Key1",
    "Name": "Key Name 1"
  },
  {
    "isSelected": true,
    "GroupKey": "G1",
    "GroupName": "Group1",
    "Key": "Key2",
    "Name": "Key Name 2"
  },
  {
    "isSelected": true,
    "GroupKey": "G2",
    "GroupName": "Group2",
    "Key": "Key1",
    "Name": "Key Name 1"
  },
  {
    "isSelected": true,
    "GroupKey": "G2",
    "GroupName": "Group2",
    "Key": "Key2",
    "Name": "Key Name 2"
  }

Output expected as below:

outputList: dataGroup[] = [
       {
          GroupKey:"G1",
          GroupName:"Group1",
          Group:[
             {
                Key:"Key1",
                Name:"Key Name 1"
             },
             {
                Key:"Key2",
                Name:"Key Name 2"
             }
          ]
       },
       {
          GroupKey:"G2",
          GroupName:"Group2",
          Group:[
             {
                Key:"Key1",
                Name:"Key Name 1"
             },
             {
                Key:"Key2",
                Name:"Key Name 2"
             }
          ]
       }
    ]

Solution

  • Here you go:

    // Change as necessary for your module loading configuration
    import _ = require("lodash");
    
    let grouped1 = _.groupBy(inputList, (dm) => dm.GroupKey);
    let outputList: dataGroup[] = Object.keys(grouped1).map((groupKey) => {
        let groupItems = grouped1[groupKey];
        return {
            GroupKey: groupKey,
            GroupName: groupItems[0].GroupName,
            Group: groupItems.map((dm) => _.pick(dm, "Key", "Name"))
        };
    });
    

    Let me know if you have any questions about how this works.