繁体   English   中英

将 object 值从一个对象数组移动到另一个对象数组

[英]Move object value from one array of objects to another

我有两个 arrays 对象,需要将第二个数组中的值移动到具有相同 ID 的第一个数组 object 中。

array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}]

array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}]

我试过合并它们,但我最终得到了重复的对象。

我希望它最终看起来如何

array1 = [{id:1, location: 'A', value: 123},{id:2, location: 'B', value: 5466},{id:3, location: 'C', value: 89484},{id:4, location: 'D', value: -4.215}]

您可以使用 Array.prototype.map( Array.prototype.map()遍历您的基本数组,同时使用Array.prototype.find()查找另一个数组以匹配id

 const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}], array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}], result = array1.map(o => ({...o, ...array2.find(_o => _o.id == o.id)})) console.log(result)
 .as-console-wrapper{min-height:100%;}

请在下面找到片段

 array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}] array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}] let result = array1.map(obj => { return {...array2.filter(obj2 => obj2.id === obj.id)[0], ...obj } }) console.log(result)

这应该有效:

array1.map( // build a second array with the new objects
       el => Object.assign( // create the merged object
               el, //          from the current object
               array2.find( // with the object in array2 with the same id
                    obj => obj.id == el.id
               )
       )
)

如果索引相同,您可以 map 并像下面一样传播 object

 const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}]; const array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}]; const merged = array1.map((a,i)=>({...a, ...array2[i]})); console.log(merged);

如果索引不同,那么您可以执行以下操作

 const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}]; const array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}]; const merged = array1.map(a=>({...a, ...array2.find(a2=>a2.id==a.id)})); console.log(merged);

暂无
暂无

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

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