Search code examples
javascriptarraysjsonecmascript-6lodash

How to do data formatting using lodash


I am creating the tree chart for the web application, where i need to pass the data in specified format. I have this data

let arr = [
  {
    "name": "jmd",
    "aname": "Asset123",
    "transformer_name": "IT1",
    "RMU": "rmu1",
    "feeder_name": "feeder",
    "pooling_station": "ppp1",
    "grid_name": "gggg1"
  }
]

expected result -

 {
         "name": "jmd",
         "children": [
           {
             "name": "ppp1",
             "children": [{
               "name": "feeder",
               "children": [{
                 "name": "rmu1",
                 "children": [{
                   "name": "IT1",
                   "children": [{
                     "aname": "Asset123"
                   }]
                 }]
               }]
             }],
           }
 }

How to do groupby multiple keys using lodash?


Solution

  • You can create a recursive function (recursiveGroupBy) that receives an array of keys by the order you want to group by.

    For each key, but the last, the function uses _.groupBy() on the key, and then maps all groups to objects with name (the group's name), and children. The children are generated by calling the recursiveGroupBy function and passing it rest of the keys, and the current group.

    For the last key we map the array, and use _.pick() to create an object with the last key and it's value.

    const { groupBy, map, pick } = _
    
    const recursiveGroupBy = ([key, ...restKeys], arr) => {  
      if(!restKeys.length) { // if last key
        return map(arr, o => pick(o, key)); // convert to an array of objects with the last key and values
      }
      
      const groups = groupBy(arr, key) // group by the current key
    
      return map(groups, (group, name) => ({ // generate the children's objects
        name,
        children: recursiveGroupBy(restKeys, group)
      }))
    }
    
    const arr = [{"name":"jmd","aname":"Asset123","transformer_name":"IT1","RMU":"rmu1","feeder_name":"feeder","pooling_station":"ppp1","grid_name":"gggg1"},{"name":"jmd","aname":"inv11","transformer_name":"itr11","RMU":"rmu11","feeder_name":"feeder3","pooling_station":"P2","grid_name":"sri"}]
    
    const result = recursiveGroupBy(['name', 'pooling_station', 'feeder_name', 'RMU', 'transformer_name', 'aname'], arr)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>