简体   繁体   English

将对象数组合并为按属性值匹配的数组

[英]Merge Object Array into Array matched by property value

I am trying to merge in an array to an existing array by a key (id).我正在尝试通过键 (id) 将数组合并到现有数组。 Is there any easy way to do this?有什么简单的方法可以做到这一点吗?

For example:例如:

people = [{id: 1, name: 'John Doe'}, {id: 2, name: 'Jane Doe'}];
places = [{id: 1, state: 'CA'}, {id: 2, state: 'AK'}];

// expected output I want is
result = [{id: 1, name: 'John Doe', places: {id: 1, state: 'CA'}}, {id: 2, name: 'Jane Doe', places: {id: 2, state: 'AK}'}}];

How can I get places property id to map into people id so basically the ID's match up and they keys are carried in?我怎样才能让地方属性 id 映射到人的 id 中,所以基本上 ID 匹配并且他们的钥匙被携带?

Here is the JS way to implement the scenario :这是实现场景的JS方法:

 const people = [{id: 1, name: 'John Doe'}, {id: 2, name: 'Jane Doe'}]; const places = [{id: 1, state: 'CA'}, {id: 2, state: 'AK'}]; const result = people.map(ppl => { ppl.places = places.find(plc => plc.id === ppl.id) return ppl; }) console.log(result) // ES6 way let res = people.map(obj => { let data = places.find(item => item.id === obj.id); return {...obj, places: data} }); console.log('ES6 way ......',res)

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

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