简体   繁体   English

合并到匹配 id 的对象数组

[英]merge to objects array matching id

two arrays两个 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?将它们合并在一起,将 id 交换为它们对应的名称和它们的宝石总和?

expected output:预期 output:

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

Use Array#reduce .使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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