`我有两个对象数组,如下所示。我想比较两个数组的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 }
];
1条答案
按热度按时间f4t66c6m1#