const array1 = [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 },
{ id: 3, name: 'Bob', age: 35 }
];
const array2 = [
{ id: 2, name: 'Alice', age: 28 },
{ id: 3, name: 'Charlie', age: 32 }
];
for (let i = 0; i < array1.length; i++) {
const element1 = array1[i];
const element2 = array2.find(item => item.id === element1.id);
if (element2) {
element1.name = element2.name;
element1.age = element2.age;
}
}
console.log(array1);
打印结果
[
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Alice', age: 28 },
{ id: 3, name: 'Charlie', age: 32 }
]