How would one take a JavaScript array of objects, such as
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} // <- duplicate key
]
and merge duplicate keys by summing the values?
In order to get something like this:
reducedObjArr = [
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:96},
{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},
{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23}
]
I have tried iterating and adding to a new array, but this didn't work:
var reducedObjArr = [];
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item = objArr[i];
key = Object.keys(item)[0];
item = item[key];
if(!result[key]) {
result[key] = item;
} else {
result[key] += item;
}
}a
key = Object.keys(item)[0]; item=item[key];
? You already know the name iskey
, so just doitem.key
orobjArr[i].key
. Also, using the[0]
index won't necessarily always give you the same property. – ContemptibleMon Sep 23 2013 00:00:00 GMT-0400
? – Dottie