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

如何深度合并JavaScript对象以保留所有层级子属性?(Redux场景)

实现对象的深度拉链式合并(适用于Redux Reducer)

普通的对象扩展运算符({...base, ...add})是浅合并,遇到同名子对象时会直接覆盖,而你需要的是递归合并所有层级属性的“拉链式合并”,可以自己实现一个递归合并函数来满足需求,同时支持用null处理属性删除。

核心实现代码

function deepMerge(base, add) {
  // 如果add不是对象,直接返回add(覆盖base属性或实现删除)
  if (typeof add !== 'object' || add === null) {
    return add;
  }
  // 如果base不是对象,直接返回add(替换原非对象属性)
  if (typeof base !== 'object' || base === null) {
    return add;
  }

  // 创建新对象,避免修改原状态(符合Redux的immutable要求)
  const merged = {...base};
  for (const key in add) {
    merged[key] = deepMerge(merged[key], add[key]);
  }
  return merged;
}

测试你的示例

用这个函数处理你给出的对象:

const base = {
    a: {
        i: {
            foo: true
        }
    }
};

const add = {
    a: {
        j: {
            foo: false
        }
    },
    b: true
};

const result = deepMerge(base, add);
console.log(result);

输出结果就是你想要的:

{
    a: {
        i: {
            foo: true
        },
        j: {
            foo: false
        }
    },
    b: true
}

支持删除属性的处理

如果需要删除某个属性,只要在add对象中将对应属性设为null即可:

const base = {
    a: {
        i: { foo: true },
        j: { foo: false }
    },
    b: true
};

const add = {
    a: {
        i: null // 删除a.i属性
    },
    b: null // 删除b属性
};

const result = deepMerge(base, add);
console.log(result);
// 输出:{ a: { j: { foo: false } } }

在Redux Reducer中使用

因为Redux要求状态是immutable的,这个函数创建新对象而不修改原状态,刚好符合要求。比如你的reducer可以这样写:

function myReducer(state = {}, action) {
  switch (action.type) {
    case 'UPDATE_STATE':
      return deepMerge(state, action.payload);
    // 其他case逻辑...
    default:
      return state;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:53:37