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

使用原生JavaScript合并特定嵌套结构对象的方法咨询

原生JavaScript合并指定结构对象的方法

针对你给出的对象结构(顶层键为年份,对应值为子对象,其中一方子对象为空),可以用以下几种原生JS方法实现合并:

方法一:手动遍历合并(结构固定时适用)

直接遍历所有年份键,对每个年份的子对象进行浅合并,空对象会被有内容的子对象覆盖:

const target = { year1: {}, year2: { someKey2: 'value2' } };
const source = { year1: { someKey1: 'value1' }, year2: {} };

const merged = {};
// 收集所有存在的年份键
const allYears = [...new Set([...Object.keys(target), ...Object.keys(source)])];

allYears.forEach(year => {
  merged[year] = { ...target[year], ...source[year] };
});

console.log(merged);
// 输出:{ year1: { someKey1: 'value1' }, year2: { someKey2: 'value2' } }

方法二:使用Object.fromEntries与Map处理动态键

如果年份键不固定,这种方法可以自动合并所有同名顶层键的子对象:

const target = { year1: {}, year2: { someKey2: 'value2' } };
const source = { year1: { someKey1: 'value1' }, year2: {} };

const merged = Object.fromEntries(
  [...Object.entries(target), ...Object.entries(source)]
    .reduce((acc, [year, obj]) => {
      acc.set(year, { ...(acc.get(year) || {}), ...obj });
      return acc;
    }, new Map())
    .entries()
);

console.log(merged);
// 输出同上

方法三:深度合并(子对象均有内容时适用)

如果目标和源对象的子对象都包含属性,需要递归合并所有层级的属性,可以用深度合并函数:

function deepMerge(target, source) {
  const result = { ...target };
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      const targetVal = result[key];
      const sourceVal = source[key];
      // 判断是否为需要合并的纯对象
      if (typeof targetVal === 'object' && targetVal !== null && 
          typeof sourceVal === 'object' && sourceVal !== null &&
          !Array.isArray(targetVal) && !Array.isArray(sourceVal)) {
        result[key] = deepMerge(targetVal, sourceVal);
      } else {
        result[key] = sourceVal;
      }
    }
  }
  return result;
}

// 示例:子对象均有属性的情况
const target = { year1: { a: 1 }, year2: { someKey2: 'value2' } };
const source = { year1: { b: 2 }, year2: { c: 3 } };

const merged = deepMerge(target, source);
console.log(merged);
// 输出:{ year1: { a: 1, b: 2 }, year2: { someKey2: 'value2', c: 3 } }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:25:37