考虑下面的两个数组:
let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}]
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}]
如何将一个对象的angle键上的值与下一个对象数组中的对应对象相加,然后返回一个或另一个对象。
结果应该是:
let ccc= [{label: "nu", angle: 7}, {label: "na", angle: 9}]
我不知道该如何解决
答案 0 :(得分:1)
您可以像这样使用Array.reduce()
和Array.findIndex()
:
let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}];
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}];
const ccc = [...aaa, ...bbb].reduce((acc, a) => {
const i = acc.findIndex(o => o.label === a.label);
if(i === -1) { acc.push(a); return acc; }
acc[i].angle += a.angle;
return acc;
}, []);
console.log(ccc);