假设有两个数组arr1
和arr2
,它们的元素都是对象,每个对象都有一个id
属性。可以使用Array.prototype.map()
和Array.prototype.find()
方法来实现将两个数组中id
相同的对象合并到一起的操作。
具体实现代码如下:
const arr1 = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const arr2 = [
{ id: 2, age: 20 },
{ id: 3, age: 30 },
{ id: 4, age: 40 }
];
const mergedArr = arr1.map(item1 => {
const item2 = arr2.find(item2 => item2.id === item1.id);
return item2 ? { ...item1, ...item2 } : item1;
});
console.log(mergedArr);
// Output:
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob', age: 20 },
// { id: 3, name: 'Charlie', age: 30 },
// { id: 4, age: 40 }
// ]
在上面的代码中,我们首先使用Array.prototype.map()
方法遍历arr1
数组中的每个元素。对于每个元素,我们使用Array.prototype.find()
方法在arr2
数组中查找id
属性值相同的元素。如果找到了,我们就使用扩展运算符...
将两个对象合并到一起,否则就返回item1
对象本身。最终得到的mergedArr
数组就是将两个数组中id
相同的对象合并到一起的结果。