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

如何使用Lodash合并两个对象并忽略null值?

使用Lodash合并对象时忽略null值,保留初始状态的对应取值

嘿,Arthur,这个问题其实用Lodash的_.mergeWith方法就能完美解决——它允许我们自定义合并规则,正好能过滤掉storedState里的null值,保留initialState的对应内容。

核心思路

_.mergeWith是Lodash合并方法的增强版,它接受一个自定义合并器函数,我们可以在这个函数里判断:如果storedState的属性值是null,就保留initialState的对应值,不进行覆盖;其他情况则沿用Lodash默认的合并逻辑(比如嵌套对象合并、非null有效值覆盖)。

完整代码示例

const _ = require('lodash');

// 你的初始状态
const initialState = {
  user: {
    name: 'Alice',
    age: 30,
    address: {
      city: 'New York',
      zip: '10001'
    }
  },
  preferences: {
    theme: 'light',
    notifications: true
  }
};

// 存储的状态,包含需要忽略的null值
const storedState = {
  user: {
    name: 'Bob',
    age: null, // 这个null不会覆盖initialState的age
    address: {
      zip: null // 这个null不会覆盖初始的zip
    }
  },
  preferences: {
    notifications: false // 非null值正常覆盖初始值
  }
};

// 自定义合并器函数
const ignoreNullMerger = (targetValue, sourceValue) => {
  // 当来源值(storedState的属性)是null时,返回目标值(initialState的属性)
  if (sourceValue === null) {
    return targetValue;
  }
  // 返回undefined时,Lodash会使用默认合并逻辑
  return undefined;
};

// 执行合并(用空对象作为目标,避免修改原状态)
const mergedState = _.mergeWith({}, initialState, storedState, ignoreNullMerger);

console.log(mergedState);

代码解释

  • 我们通过_.mergeWith创建一个新的合并对象(第一个参数传空对象,是为了不修改原始的initialState和storedState,这在状态管理里是最佳实践)。
  • 合并器函数ignoreNullMerger中,只要sourceValue(storedState的属性值)是null,就返回targetValue(initialState的对应属性值),这样就跳过了null值的覆盖。
  • 如果返回undefined,Lodash会自动使用默认的合并规则,比如合并嵌套对象、用非null的有效值覆盖初始值。

额外扩展

如果你需要同时忽略null和undefined值,可以把判断条件改成:

if (sourceValue == null) { // 因为null == undefined为true,会同时匹配两者
  return targetValue;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:17:07