javascript 比较2个对象数组,并向具有匹配id的对象添加一个属性

fruv7luv  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(149)

`我有两个对象数组,如下所示。我想比较两个数组的id,并返回带有布尔值的isSomeProperty。

const arr1 = [
{ id: 001, name: 'abc' },
{ id: 002, name: 'def' },
{ id: 003, name: 'ghi' },
{ id: 004, name: 'jkl' },
{ id: 005, name: 'mno' }
];

const arr2 = [
{ id: 001, name: 'abc' },
{ id: 002, name: 'def' }
];

arr1.forEach((item1) => {
    arr2.forEach((item2) => {
if (item1.id === item2.id) {
return {
...item1,
isSomeProperty: true;
}
} else {
return {
...item1,
isSomeProperty: false;
}
}
});
});
return arr1;

有没有一种方法可以避免使用两个forEach循环,并以一种有效的方式完成。
预期输出:

const arr1 = [  
{ id: 001, name: 'abc', isSomeProperty: true },  
{ id: 002, name: 'def', isSomeProperty: true },  
{ id: 003, name: 'ghi', isSomeProperty: false },  
{ id: 004, name: 'jkl', isSomeProperty: false },  
{ id: 005, name: 'mno', isSomeProperty: false } 
];
f4t66c6m

f4t66c6m1#

const arr1 = [
  { id: 001, name: 'abc' },
  { id: 002, name: 'def' },
  { id: 003, name: 'ghi' },
  { id: 004, name: 'jkl' },
  { id: 005, name: 'mno' }
];

const arr2 = [
  { id: 001, name: 'abc' },
  { id: 002, name: 'def' }
];

const result = arr1.map(item1 => {
  const item2 = arr2.find(item2 => item1.id === item2.id);
  return {
    ...item1,
    isSomeProperty: !!item2 // convert item2 to a boolean value
  };
});

console.log(result);

相关问题