Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge object & sum a single property javascript

i have an array like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
  },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  },
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  }
]

What i want from this to merge similar item_guid into one object and quantity get summed up like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:6
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:6
  }
]

I know this can be achieved some loop, instead I'm looking for solutions that uses lodash or EcmaScript2015 code to make our life easier

like image 242
Faysal Ahmed Avatar asked Oct 26 '16 12:10

Faysal Ahmed


1 Answers

A simple approach:

Loop over data and create an object where key will be unique id and its value will be quantity. Then loop back over object's keys and create objects.

var data = [{ item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }]

var r = {};
data.forEach(function(o){
  r[o.item_guid] = (r[o.item_guid] || 0) + o.quantity;
})

var result = Object.keys(r).map(function(k){
  return { item_guid: k, quantity: r[k] }
});
console.log(result)
like image 125
Rajesh Avatar answered Nov 03 '22 00:11

Rajesh