You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何通过对象合并覆盖嵌套对象的部分属性

解决嵌套对象属性的部分覆盖问题

嘿,我完全懂你遇到的这个坑!你用的对象扩展运算符(...)其实是浅合并——它只会处理对象的顶层属性,碰到嵌套对象的时候,会直接用新对象把旧的嵌套对象整个替换掉,而不会深入到内层去合并具体的属性。

看你的例子,customer.applicant是一个完整的对象,当你用{ ...application, ...customer }合并时,顶层的applicant键会直接被customer里的版本覆盖,自然就丢失了原来application.applicant.age这个属性。

几种可行的解决方案

1. 手动针对嵌套对象做合并

如果你的嵌套层级不深,最直接的方法就是单独处理嵌套的applicant对象,把新旧两个applicant的属性合并后再赋值回去:

const customer = { applicant: { first_name: 'john' } }
const application = { applicant: { first_name: 'edward', age: 50 }, income: { salary: 500 } }

const merged = {
  ...application, // 先复制所有顶层属性
  applicant: {
    ...application.applicant, // 复制原来applicant的所有属性
    ...customer.applicant     // 用customer的applicant属性覆盖对应值
  }
}

console.log(merged)
// 输出:{ applicant: { first_name: 'john', age: 50 }, income: { salary: 500 } }

这样就能精准地只覆盖first_name,同时保留其他嵌套属性。

2. 写一个通用的深合并函数

如果你的项目里经常需要处理多层嵌套对象的合并,写一个递归的深合并函数会更方便:

function deepMerge(target, source) {
  // 先复制目标对象的顶层属性
  let result = { ...target };
  
  // 遍历源对象的每个属性
  for (const key in source) {
    // 如果当前属性是对象(且不是数组),就递归合并
    if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
      result[key] = deepMerge(result[key] || {}, source[key]);
    } else {
      // 否则直接覆盖
      result[key] = source[key];
    }
  }
  
  return result;
}

const merged = deepMerge(application, customer);
console.log(merged)
// 同样得到预期结果:{ applicant: { first_name: 'john', age: 50 }, income: { salary: 500 } }

这个函数会自动处理所有层级的嵌套对象,不管嵌套多深都能正确合并属性,而不是直接替换整个对象。

3. 借助第三方工具(可选)

如果你不想自己写函数,也可以用像Lodash的_.merge方法,它本身就提供了成熟的深合并功能,但前提是你愿意引入第三方库。

内容的提问来源于stack exchange,提问作者Ryan H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:33:13