Sum javascript object propertyA values with same object propertyB in array of objects

前端 未结 9 2481
醉梦人生
醉梦人生 2020-11-22 04:48

How would one take a javascript array of objects such as:

my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-04         


        
9条回答
  •  渐次进展
    2020-11-22 05:40

    var targetObj = {};
    for (var i = 0; i < objArr.length; i++) {
        if (!targetObj.hasOwnProperty(objArr[i].key)) {
            targetObj[objArr[i].key] = 0;
        }
        targetObj[objArr[i].key] += objArr[i].val;
    }
    

    http://jsfiddle.net/HUMxp/

提交回复
热议问题