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

TypeScript如何忽略null和undefined值比较两个对象

解决方案

方法一:使用Lodash先清理对象再比较

你的问题核心是_.isEqualWith的自定义函数无法处理「一个对象存在某属性但值为null/undefined,另一个对象无该属性」的场景——默认这种情况会直接判定不相等。最直接的解决方式是先过滤掉两个对象中值为null或undefined的属性,再比较清理后的对象:

import _ from 'lodash';

const obj = { 'id': 5, 'name': null };
const other = { 'id': 5 };

// 过滤值为 null/undefined 的属性
const cleanObj = _.omitBy(obj, val => val == null);
const cleanOther = _.omitBy(other, val => val == null);

// 比较清理后的对象
const isEqual = _.isEqual(cleanObj, cleanOther); // 结果为 true

方法二:自定义实现(无需Lodash)

如果不想依赖Lodash,可以自己实现清理和比较逻辑,支持嵌套对象:

const obj = { 'id': 5, 'name': null };
const other = { 'id': 5 };

// 清理对象:移除值为 null/undefined 的属性
function cleanObject<T extends object>(obj: T): Partial<T> {
  return Object.fromEntries(
    Object.entries(obj).filter(([_, val]) => val != null)
  );
}

// 深度比较两个对象是否相等
function isDeepEqual(a: object, b: object): boolean {
  const cleanedA = cleanObject(a);
  const cleanedB = cleanObject(b);

  // 属性数量不同直接返回false
  if (Object.keys(cleanedA).length !== Object.keys(cleanedB).length) {
    return false;
  }

  // 逐个比较属性值
  for (const key of Object.keys(cleanedA)) {
    const valA = cleanedA[key as keyof typeof cleanedA];
    const valB = cleanedB[key as keyof typeof cleanedB];

    // 嵌套对象递归比较
    if (typeof valA === 'object' && valA != null && typeof valB === 'object' && valB != null) {
      if (!isDeepEqual(valA as object, valB as object)) {
        return false;
      }
    } else if (valA !== valB) {
      return false;
    }
  }
  return true;
}

const result = isDeepEqual(obj, other); // 结果为 true

为什么你的原代码不生效?

_.isEqualWith的自定义函数仅负责属性值的比较,但不会修改Lodash默认的属性存在性检查逻辑。当obj有name: null而other没有name属性时,Lodash会认为这两个对象的属性集合不一致,直接返回false,不会触发你的自定义比较逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:12:30