使用angularjs在JSON数组中的相同ID的总和

时间:2019-06-11 05:02:21

标签: arrays angularjs sum

我有一个如下的json数组

var arrayVal = [{id:"1", sAge: 20, eAge:30},{id:"2", sAge: 30, eAge:50},{id:"2", sAge: 20, eAge:40},{id:"3", Aage: 20, eAge:50},{id:"5", sAge: 10, eAge:30}];

我想对每个id的sAge和eAge求和,如果存在相同id的多个diff值,则求和最终值。输出应如下所示

1 = 10,
2 = 40,
3 = 30,
5 = 20

1 个答案:

答案 0 :(得分:0)

与您的(?)previous question几乎相同:

var array = [{id:"1", sAge: 20, eAge:30},{id:"2",sAge:30, eAge:50},{id:"2",sAge:20,eAge:40},{id:"3",sAge:20,eAge:50},{id:"5",sAge:10,eAge:30}];

const ages = array.reduce((a, {id, sAge, eAge}) => (a[id] = (a[id] || 0) + eAge - sAge, a), {});

console.log(ages);

注意:还修复了对象中的拼写错误。