Home > Article > Web Front-end > How to Efficiently Sum Values of Similar Keys in JavaScript Objects?
Given an array of JavaScript objects, how can you effectively sum the values associated with similar keys?
To achieve this, we can employ the following steps:
Consider the example array:
var obj = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];
Applying the above approach:
// Create a holder object to sum values for similar names 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; } }); // Populate a new array with the summed values var obj2 = []; for (var prop in holder) { obj2.push({ name: prop, value: holder[prop] }); } // Output the result console.log(obj2);
Expected output:
[ { 'name': 'P1', 'value': 300 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ]
The above is the detailed content of How to Efficiently Sum Values of Similar Keys in JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!