Sum javascript object propertyA values with same object propertyB in array of objects
You should be assigning each object not found to the result with its .key
property.
If it is found, then you need to add its .val
.
var temp = {};var obj = null;for(var i=0; i < objArr.length; i++) { obj=objArr[i]; if(!temp[obj.key]) { temp[obj.key] = obj; } else { temp[obj.key].val += obj.val; }}var result = [];for (var prop in temp) result.push(temp[prop]);
Also, part of the problem was that you were reusing the item
variable to reference the value of .key
, so you lost reference to the object.
Rather than using a for loop and pushing values, you can directly use map and reduce:
let objArr = [ {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42}, {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78}, {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23}, {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}];// first, convert data into a Map with reducelet counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev;}, new Map());// then, map your counts object back to an arraylet reducedObjArr = [...counts].map(([key, value]) => { return {key, value}})console.log(reducedObjArr);
Simpler reduce than posted elsewhere
const objArr = [{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:42},{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23},{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:54}];const output = objArr.reduce((accumulator, cur) => { let date = cur.key; let found = accumulator.find(elem => elem.key === date) if (found) found.val += cur.val; else accumulator.push(cur); return accumulator;}, []);console.log(output)