Sum similar keys in an array of objects

First iterate through the array and push the ‘name’ into another object’s property. If the property exists add the ‘value’ to the value of the property otherwise initialize the property to the ‘value’. Once you build this object, iterate through the properties and push them to another array.

Here is some code:

var obj = [
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P2', 'value': 200 },
    { 'name': 'P3', 'value': 450 }
];

var holder = {};

obj.forEach(function(d) {
  if (holder.hasOwnProperty(d.name)) {
    holder[d.name] = holder[d.name] + d.value;
  } else {
    holder[d.name] = d.value;
  }
});

var obj2 = [];

for (var prop in holder) {
  obj2.push({ name: prop, value: holder[prop] });
}

console.log(obj2);

Hope this helps.

Leave a Comment