使用 Object.assign() 方法将要附加的对象与原始对象合并,而不是直接赋值替换原始对象。以下是示例代码:
// 原始对象 const originalObject = { name: 'Alice', age: 25, address: { street: '123 Main St', city: 'New York', state: 'NY' } };
// 要附加的对象 const newObject = { address: { state: 'CA', zip: '90210' } };
// 错误的方式:直接赋值会替换原始对象 originalObject = newObject;
// 正确的方式:使用 Object.assign() 方法合并对象 const mergedObject = Object.assign({}, originalObject, newObject); console.log(mergedObject); /* { name: 'Alice', age: 25, address: { street: '123 Main St', city: 'New York', state: 'CA', zip: '90210' } } */