javascript - Sum similar keys in an array of objects -
i have array of objects following: -
[ { 'name': 'p1', 'value': 150 }, { 'name': 'p1', 'value': 150 }, { 'name': 'p2', 'value': 200 }, { 'name': 'p3', 'value': 450 } ]
i need add (summation) , other mathematical operation calculate average object same name appearing in it. like: -
[ { 'name': 'p1', 'value': 300 }, { 'name': 'p2', 'value': 200 }, { 'name': 'p3', 'value': 450 } ]
would appreciate can get.
thanks in advance!
first iterate through array , push 'name' object's property. if property exists add 'value' value of property otherwise initialize property 'value'. once build object, iterate through properties , push them array.
here 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 helps.
Comments
Post a Comment