[英]Move object value from one array of objects to another
I have two arrays of objects and need to move the value from the 2nd array in to the first array object with the same id.我有两个 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}]
Ive tried merging them but i just end up with duplicate objects.我试过合并它们,但我最终得到了重复的对象。
how i want it to end up looking like我希望它最终看起来如何
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}]
You may traverse your base array with Array.prototype.map()
, using Array.prototype.find()
along the way to lookup another array for matching id
:您可以使用 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%;}
Please find below snippet请在下面找到片段
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)
This should work:这应该有效:
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
)
)
)
If index are same you can map and spread the object like below如果索引相同,您可以 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);
If the index are not same then you can do like below如果索引不同,那么您可以执行以下操作
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.