方法一:
let A = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' }
];
let B = [
{ id: 2, age: 25 },
{ id: 3, age: 30 }
];
A = A.map(aItem => {
const bItem = B.find(bItem => bItem.id === aItem.id);
return { ...aItem, ...bItem };
});
console.log(A);
打印出来的数据:
[
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 }
]
方法二:
const A = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
const B = [{ id: 1, age: 25 }, { id: 2, age: 30 }, { id: 3, age: 22 }];
const mergeById = (arr1, arr2) => {
return arr2.reduce((acc, current) => {
const foundItem = arr1.find(item => item.id === current.id);
if (foundItem) {
acc.push({ ...foundItem, ...current });
}
return acc;
}, []);
};
const mergedArray = mergeById(A, B);
console.log(mergedArray);
打印出来的数据:
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Doe', age: 30 }
]