Edwin Bermejo Edwin Bermejo - 2 days ago 5
AngularJS Question

Using lodash .groupBy. How to group object inside an object

I'm using lodash's _.groupBy to come up with the following data:

{
"Generic Drugs":[
{
itemDes: "Dulcolax",
itemGeneric: "Bisacodyl",
price: '10'
},
{
itemDes: "Celine",
itemGeneric: "Ascorbic Acid",
price: '10'
},
{
itemDes: "Vitamic C",
itemGeneric: "Ascorbic Acid",
price: '10'
}
],
"None-generic Drugs" : [
{
itemDes: "test 1",
itemGeneric: "",
price: '10'
},
{
itemDes: "test 2",
itemGeneric: "",
price: '10'
}
]
}


I wanted to group the objects in Generic Drugs object by the property itemGeneric to come up an output like this:

{
"Generic Drugs":[
"Ascorbic Acid" : [
{ itemDes: "Celine" },
{ itemDesc: "Vitamin C" }
],
"Bisacodyl" : [
{ itemDes: "Dolculax" }
]
"None-generic Drugs" : [
{
itemDes: "test 1",
itemGeneric: "",
price: '10'
},
{
itemDes: "test 2",
itemGeneric: "",
price: '10'
}
]
}


Please somebody help me with this problem. Thanks for the answers. :)

Answer

Use _.mapValues() on the grouped data, and group each value by the 'itemGeneric':

_.mapValues(grouped, function(group, key) {
  if(key === 'Generic Drugs') {
      return _.groupBy(group, 'itemGeneric');
  }

  return group;
});

var grouped = {
  "Generic Drugs": [{
    itemDes: "Dulcolax",
    itemGeneric: "Bisacodyl",
    price: '10'
  }, {
    itemDes: "Celine",
    itemGeneric: "Ascorbic Acid",
    price: '10'
  }, {
    itemDes: "Vitamic C",
    itemGeneric: "Ascorbic Acid",
    price: '10'
  }],
  "None-generic Drugs": [{
    itemDes: "test 1",
    itemGeneric: "",
    price: '10'
  }, {
    itemDes: "test 2",
    itemGeneric: "",
    price: '10'
  }]
};

var result = _.mapValues(grouped, function(group, key) {
  if(key === 'Generic Drugs') {
      return _.groupBy(group, 'itemGeneric');
  }
  
  return group;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

If the original data item is something like this:

  {
      type: "Generic Drugs",
      itemDes: "Dulcolax",
      itemGeneric: "Bisacodyl",
      price: '10'
  }

You can do:

_(originalData).groupBy('type').mapValues(grouped, function(group, key) {
    if(key === 'Generic Drugs') {
      return _.groupBy(group, 'itemGeneric');
    }

    return group;
});
Comments