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

前端 未结 9 2662
醉梦人生
醉梦人生 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:29

    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.

提交回复
热议问题