简体   繁体   中英

merge to objects array matching id

two arrays

arr1 = [
{id: 1, name: john doe},
{id: 2, name: uncle bob},
{id: 3, name: patrick star}
]

arr2 = [
{id: 1, gems: 500},
{id: 2, gems: 1000},
{id: 3, gems: 750},
{id: 2, gems: 8000},
{id: 3, gems: 7750},
{id: 1, gems: 1200},
{id: 3, gems: 950},
]

merge them together swapping id to their corresponding names and the sum of their gems?

expected output:

arr3 = [
{name: 'john doe', gems: 1700}
{name: 'uncle bob', gems: 9000}
{name: 'patrick star', gems: 9450}
]

Use Array#reduce .

 let arr1 = [ {id: 1, name: 'john doe'}, {id: 2, name: 'uncle bob'}, {id: 3, name: 'patrick star'} ], arr2 = [ {id: 1, gems: 500}, {id: 2, gems: 1000}, {id: 3, gems: 750}, {id: 2, gems: 8000}, {id: 3, gems: 7750}, {id: 1, gems: 1200}, {id: 3, gems: 950}, ]; let arr3 = arr2.reduce((acc,curr)=>{ let other = acc.find(({id})=>id===curr.id); other.gems = (other.gems || 0) + curr.gems; return acc; }, arr1).map(({name,gems})=>({name,gems})); console.log(arr3);

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