如何从第二个对象中的每个对象复制技能 属性 并根据 属性 id 为第一个数组中的每个对象设置该技能 属性? (JS)

How to copy skill property from each object in the 2nd and set that skill property for each object in the 1st array based on property id? (JS)

我有 2 个对象数组。两个数组的每个对象都具有相同的长度和相同的 id 属性:

const arr1 = [{id:1, name:'Dave', email:'email1@gmail.com'}, {id:2, name:'Jane', email:'email2@gmail.com'}]
const arr2 = [{id:1, profession:'programmer', skill:'JS'}, {id:2, profession:'Sales person', skill:'sales'}]

如何从 arr2 中为每个对象复制技能 属性,并通过检查相关的 属性 id 将其设置在第一个对象数组中?

你可以这样做。

const arr1 = [{id: 1, name: "Dave", email: "email1@gmail.com"}, {id: 2, name: "Jane", email: "email2@gmail.com"}];
const arr2 = [{id: 1, profession: "programmer", skill: "JS"}, {id: 2, profession: "Sales person", skill: "sales"}];

console.log(arr1);

arr2.forEach((el2) => {
  let result = arr1.find((el1) => el1.id === el2.id)
  if (result) {
   result.skill= el2.skill;
  }
})

console.log(arr1);

For each value in arr1, try to find arr2 中的相应值并相应地更新技能 属性:

arr1.forEach(v1 => v1.skill = arr2.find(v2 => v1.id === v2.id)?.skill);

完整片段:

const arr1 = [
  {id:1, name:'Dave', email:'email1@gmail.com'},
  {id:2, name:'Jane', email:'email2@gmail.com'}
];
const arr2 = [
  {id:1, profession:'programmer', skill:'JS'},
  {id:2, profession:'Sales person', skill:'sales'}
];

arr1.forEach(v1 => v1.skill = arr2.find(v2 => v1.id === v2.id)?.skill);

console.log(arr1);