【发布时间】:2021-12-30 08:13:01
【问题描述】:
我正在开发一个 JS 项目,我需要在其中覆盖包含嵌套对象的对象中的一些值。
我通常会使用以下内容:
const merged = { ...application, ...customer }
这样customer 内的任何数据都可以覆盖application。
但是,在我的示例中,customer 覆盖了整个 applicant 嵌套对象,我只需要覆盖该对象中的名称?
我整理了一个 JS fiddle,可以在 here 找到,我错过了什么?
const customer = {
applicant: {
first_name: 'john'
}
}
const application = {
applicant: {
first_name: 'edward',
age: 50
},
income: {
salary: 500
}
}
const merged = { ...application, ...customer }
console.log(merged)
在merged 中,我希望first_name 是“John”,而其他一切都保持不变。
【问题讨论】:
-
我错过了什么? - 这不是递归操作。
...application获取application的字段,所以applicant和income,然后...customer用自己的字段覆盖applicant。 -
这能回答你的问题吗? How to deep merge instead of shallow merge?
标签: javascript object ecmascript-6