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

JS中如何用另一对象更新目标对象并忽略原对象无的字段

在JavaScript中用对象更新另一个对象并忽略不存在的字段

要实现用源对象(Object B)更新目标对象(Object A),同时只保留目标对象原本存在的字段,忽略源对象中目标没有的字段,需要递归处理嵌套的对象和数组,确保字段结构完全遵循目标对象。

原始示例对象

// 目标对象:保留字段结构
const objA = [
  {
    "title": "herry patter",
    "actors": [
      {
        "name": "Harry",
        "feature": "lighting"
      },
      {
        "name": "Ron",
        "feature": "Red"
      }
    ]
  }
];

// 更新源对象:仅使用目标存在的字段进行更新
const objB = [
  {
    "title": "harry potter",
    "nothingHere": "bybye",
    "actors": [
      {
        "name": "Harry Potter",
        "feature": "lighting Scar"
      },
      {
        "name": "Hermione",
        "feature": "smart"
      }
    ]
  }
];

实现核心函数

这个递归函数会严格按照目标对象的字段结构,用源对象对应字段的值进行更新:

function updateTarget(target, source) {
  // 处理数组:遍历每个元素递归更新
  if (Array.isArray(target)) {
    return source.map((item, index) => updateTarget(target[index], item));
  }
  // 处理对象:仅遍历目标对象的键,确保只保留原有字段
  if (typeof target === 'object' && target !== null) {
    const updated = { ...target };
    Object.keys(target).forEach(key => {
      if (source.hasOwnProperty(key)) {
        updated[key] = updateTarget(target[key], source[key]);
      }
    });
    return updated;
  }
  // 基础类型直接用源对象的值覆盖
  return source;
}

// 执行更新
const result = updateTarget(objA, objB);
console.log(JSON.stringify(result, null, 2));

运行结果

[
  {
    "title": "harry potter",
    "actors": [
      {
        "name": "Harry Potter",
        "feature": "lighting Scar"
      },
      {
        "name": "Hermione",
        "feature": "smart"
      }
    ]
  }
]

逻辑说明

  • 数组处理:遍历源数组的每个元素,和目标数组对应位置的元素递归更新,保证数组结构一致
  • 对象处理:只遍历目标对象自身的键,源对象中存在的键才会更新,不存在的直接忽略(比如示例中的nothingHere)
  • 嵌套结构:递归处理所有嵌套的对象和数组,深层字段也会遵循目标对象的结构进行更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:15:48