简体   繁体   中英

How to change object value within an array of objects with one from another array of objects?

Considering the two arrays bellow:

let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}]
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}]

How can I add the value on the key from one object with the corresponding one from the next array of objects and return one object or the other.

the result should be:

let ccc= [{label: "nu", angle: 7}, {label: "na", angle: 9}]

I have no idea how to solve this

You can use Array.reduce() and Array.findIndex() like this:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM