Problem:
Given an array of objects, determine a method to compute the sum (or other mathematical operations) of values associated with objects that share the same key.
Example:
Consider the following array of objects:
[ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ]
The desired output would sum the 'value' property for objects with matching 'name' properties, resulting in:
[ { 'name': 'P1', 'value': 300 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ]
Solution:
The solution involves iterating through the input array, aggregating identical key values into a separate object.
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; } });
The resulting holder object will contain key-value pairs where the keys are unique name values, and the values are the sum of associated value properties.
{ 'P1': 300, 'P2': 200, 'P3': 450 }
To generate the desired output, iterate through the properties of the holder object and create new objects:
var obj2 = []; for (var prop in holder) { obj2.push({ name: prop, value: holder[prop] }); }
The final result, stored in obj2, fulfills the requirements of summing values for objects with similar keys.
The above is the detailed content of How to Sum Values of Identical Keys in an Array of JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!