我正在处理一个JS项目,在该项目中,我需要覆盖包含嵌套对象的对象中的一些值。
我通常会使用以下内容:
const merged = { ...application, ...customer }
使得customer
内部的任何数据都可以覆盖application
。
但是,在我的示例中,customer
覆盖了整个applicant
嵌套对象,而我只需要覆盖该对象中的名称?
我整理了一个JS小提琴,可以在这里找到,我缺少什么?
const customer = {
applicant: {
first_name: 'john'
}
}
const application = {
applicant: {
first_name: 'edward',
age: 50
},
income: {
salary: 500
}
}
const merged = { ...application, ...customer }
console.log(merged)
在CCD_ 5中,我期望CCD_;约翰;而其他一切都保持得体。
要通过扩展替换的属性必须位于对象的顶层。在这种情况下,您获取申请的顶级属性,即申请人和收入,然后用客户的属性替换申请人的属性。如果你想替换这个名字,你需要类似的东西
const merged = {
...application,
applicant: {...application.applicant, ...customer.applicant}
};
使用lodash 可以轻松做到这一点
const merged = _.merge(customer, application)
https://lodash.com/docs/4.17.15#merge