Search code examples
javascriptlodash

lodash using groupBy on Object


I want to use the groupBy from lodash and I want to achieve something like below. I have this code and I want to convert it from this

 [{
    id: 1,
    name: 'campaign_application_view',
    description: 'Campaign Apply - View',
    category: 'Campaign'
  }, 
  {
    id: 2,
    name: 'pixel_application_view',
    description: 'Pixel Apply - View',
    category: 'Pixels'
  }
 ];

To this

{
  Campaign: {
    selected: [],
    items: [{
        id: 1,
        name: 'campaign_application_view',
        description: 'Campaign Apply - View',
        category: 'Campaign'
      }
    ]
  },
  Pixels: {
    selected: [],
    items: [{
        id: 2,
        name: 'pixel_application_view',
        description: 'Pixel Apply - View',
        category: 'Pixels'
      }
    ]
  }
}
  1. add keys to the items.
  2. add another key

lodash _groupBy just lets me group it like {Campaign: [], Pixels: []}


Solution

  • After grouping use _.mapValues() to convert to the required form:

    const arr = [{"id":1,"name":"campaign_application_view","description":"Campaign Apply - View","category":"Campaign"},{"id":2,"name":"pixel_application_view","description":"Pixel Apply - View","category":"Pixels"}];
    
    const result = _.mapValues(
      _.groupBy(arr, 'category'),
      items => ({
        selected: [],
        items
      })
    );
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>