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

时间:2020-07-08 11:04:53

标签: javascript arrays object

我有两个对象数组,需要将值从第二个数组移到具有相同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}]

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

我希望它最终看起来像

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}]

4 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.map()Array.prototype.find()遍历您的 base 数组,并使用{{3}}查找另一个与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%;}

答案 1 :(得分:0)

请在下面的代码段中找到

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)

答案 2 :(得分:0)

这应该有效:

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

答案 3 :(得分:0)

如果索引相同,则可以如下所示映射和散布对象

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

相关问题