vue两个数组合并不同项
时间: 2023-09-15 21:19:06 浏览: 44
可以使用 `Array.prototype.map()` 和 `Array.prototype.find()` 方法来实现合并不同项的两个数组。具体步骤如下:
1. 遍历第一个数组,对于每一项,使用 `Array.prototype.find()` 方法在第二个数组中查找是否有相同的项。
2. 如果找到了相同的项,则将两个数组中对应位置的项合并成一个对象,并将其添加到结果数组中。
3. 如果没有找到相同的项,则将第一个数组中对应位置的项直接添加到结果数组中。
4. 最后再将第二个数组中剩余的项也添加到结果数组中。
示例代码如下:
```javascript
const arr1 = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }];
const arr2 = [{ id: 2, age: 10 }, { id: 3, age: 20 }, { id: 4, age: 30 }];
const mergedArr = arr1.map(item1 => {
const item2 = arr2.find(item2 => item1.id === item2.id);
return item2 ? { ...item1, ...item2 } : item1;
}).concat(arr2.filter(item2 => !arr1.find(item1 => item1.id === item2.id)));
console.log(mergedArr);
// 输出:[{ id: 1, name: 'A' }, { id: 2, name: 'B', age: 10 }, { id: 3, name: 'C', age: 20 }, { id: 4, age: 30 }]
```
在上面的示例中,先定义了两个数组 `arr1` 和 `arr2`,它们分别代表了两个不同的对象数组。然后通过 `map()` 方法遍历了 `arr1` 数组,对于每一个元素,在 `arr2` 中通过 `find()` 方法查找是否有相同的项,如果找到了相同的项,则将两个数组中对应位置的项合并成一个对象,并将其添加到结果数组中。如果没有找到相同的项,则将第一个数组中对应位置的项直接添加到结果数组中。最后再将第二个数组中剩余的项也添加到结果数组中,这里使用了 `filter()` 方法。
最终输出的 `mergedArr` 数组就是合并了不同项的两个数组。