javascript中相同对象名的总和

时间:2017-01-24 09:25:28

标签: javascript jquery json object

嗨朋友我是javascript的初学者,我如何总结对象名称对应值的相同n并将结果推送到新数组。看这是示例对象

var obj_1 ={'delivered':10,'due':11,'team_name':'UK'}; var obj_2 ={'delivered':10,'due':11,'team_name':'US'}; var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};

但我希望此输出[UK:{'delivered':20,'due':22},US:{'delivered':10,'due':11}],所以请帮助我下一步做什么

4 个答案:

答案 0 :(得分:4)

您可以先创建对象数组,然后reduce()返回一个对象。



var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};

var result = [obj_1, obj_2, obj_nth].reduce(function(r, e) {
  if(!r[e.team_name]) {
    r[e.team_name] = {delivered:0,due:0}
  }
  r[e.team_name].delivered += e.delivered
  r[e.team_name].due += e.due
  return r
}, {})

console.log(result)




答案 1 :(得分:1)

const newArray = initialArray.map(({team_name, ...restProps}) => {
  return {
    [team_name]: {...restProps}
  };
});

请参阅:

答案 2 :(得分:0)

var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};

function sum_all() { 
    var sum={}; 
    for(var i=0;i<arguments.length;i++) { 
        obj = arguments[i]; 
        if (!sum[obj.team_name]) { 
            sum[obj.team_name]={'delivered':0,'due':0}; 
        } 
        sum[obj.team_name].delivered += obj.delivered; 
        sum[obj.team_name].due += obj.due;    
    } 
    return sum; 
}

var sum = sum_all(obj_1,obj_2,obj_nth);

console.log(sum);

您的控制台输出将是:

sum
Object
  UK: Object
      delivered: 20
      due: 22

  US: Object
      delivered: 10
      due: 11

答案 3 :(得分:0)

将这些对象存储在array中,例如:

var myObjects = [
    {'delivered':10,'due':11,'team_name':'UK'},
    {'delivered':10,'due':11,'team_name':'US'},
    {'delivered':10,'due':11,'team_name':'UK'}
];

创建一个新对象,您可以在其中存储结果:

var results = {};

然后使用for循环(as it is generally faster)迭代数组,并根据team_name添加其他属性:

for (var i = 0; i <= myObjects.length; i++) {
    if (typeof results[myObjects[i].team_name] !== undefined) {
        results[myObjects[i]].delivered += myObjects[i].delivered;
        results[myObjects[i]].due += myObjects[i].due; 
    } else {
        // Set 0 to these properties if the entry didn't exist
        results[myObjects[i]].delivered = 0;
        results[myObjects[i]].due = 0;
    }
}