简体   繁体   中英

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.

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 :

 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

 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);

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