簡體   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