我有一个如下的json数组
var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", Aage: 20, eAge:50},{id:"4",name:"D", sAge: 10, eAge:30}];
我想对每个id的sAge和eAge求和,如果存在相同id的多个diff值,则求和最终值。为此,我有以下代码
const ages = array.reduce((a, {id, sAge, eAge}) => (a[id] = (a[id] || 0) + eAge - sAge, a), {});
console.log(ages);
上述代码段的输出如下
{
"1": 20,
"2": 50,
"3": 20,
"4": 10
}
但是如果我想在使用reduce()之后获得如下数组,那我该如何实现呢?
[{id:"1",name:"A", hours:"20"},{id:"2",name:"B", hours:"50"},{id:"3",name:"C", hours:"20"},{id:"5",name:"D", hours:"10"}]
答案 0 :(得分:2)
以下内容可以完成工作,但我没有获得您的期望值
var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", sAge: 20, eAge:50},{id:"5",name:"D", sAge: 10, eAge:30}];
const ages = Object.values(arrayVal.reduce((a, {id, name, sAge, eAge}) => {
let difference = eAge - sAge;
if(a.hasOwnProperty(id)) {
a[id].hours+= difference;
} else {
a[id] = {
id:id,
name:name,
hours:difference
}
}
return a;
}, {}));
输出
[
{
"id": "1",
"name": "A",
"hours": 10
},
{
"id": "2",
"name": "B",
"hours": 40
},
{
"id": "3",
"name": "C",
"hours": 30
},
{
"id": "5",
"name": "D",
"hours": 20
}
]