一个人将如何采用一个 javascript 对象数组,例如:
my 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}]
并通过对值求和来合并重复的键。为了得到这样的东西:
my 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}]
我尝试迭代并添加到一个新数组,但这不起作用:
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