小编典典

根据键合并两个对象数组

javascript

我有两个数组:

阵列1:

[
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
]

和数组2:

[
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
]

我需要基于合并这两个数组,id并获得此:

[
  { id: "abdc4051", date: "2017-01-24", name: "ab" },
  { id: "abdc4052", date: "2017-01-22", name: "abc" }
]

我如何在不迭代低谷的情况下做到这一点Object.keys


阅读 284

收藏
2020-05-01

共1个答案

小编典典

你可以这样-

let arr1 = [

    { id: "abdc4051", date: "2017-01-24" },

    { id: "abdc4052", date: "2017-01-22" }

];



let arr2 = [

    { id: "abdc4051", name: "ab" },

    { id: "abdc4052", name: "abc" }

];



let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));



console.log(arr3);

如果arr1arr2的顺序不同,请使用以下代码:

let arr1 = [

  { id: "abdc4051", date: "2017-01-24" },

  { id: "abdc4052", date: "2017-01-22" }

];



let arr2 = [

  { id: "abdc4051", name: "ab" },

  { id: "abdc4052", name: "abc" }

];



let merged = [];



for(let i=0; i<arr1.length; i++) {

  merged.push({

   ...arr1[i],

   ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}

  );

}



console.log(merged);

如果arr1arr2以相同的顺序使用

let arr1 = [

  { id: "abdc4051", date: "2017-01-24" },

  { id: "abdc4052", date: "2017-01-22" }

];



let arr2 = [

  { id: "abdc4051", name: "ab" },

  { id: "abdc4052", name: "abc" }

];



let merged = [];



for(let i=0; i<arr1.length; i++) {

  merged.push({

   ...arr1[i],

   ...arr2[i]

  });

}



console.log(merged);
2020-05-01