Javascript 使用 lodash isEqual 比较具有函数的对象

Javascript compare objects having functions using lodash isEqual

如果两个对象有函数,如何比较它们是否相等?在抛出函数之前,lodash 的 isEqual 工作得很好:

_.isEqual({
    a: 1,
    b: 2
}, {
    b: 2,    
    a: 1
});

// -> true

_.isEqual({
    a: 1,
    b: 2,
    c: function () {
        return 1;
    }
}, {
    a: 1,    
    b: 2,
    c: function () {
          return 1;
    }
});

// -> false

正如 lodash 文档所述:

Functions and DOM nodes are not supported.

https://lodash.com/docs#isEqual

您确定要比较功能吗?如果您只关心比较每个 属性 不是函数的情况,使用 lodash 很容易做到:

var o1 = { a: 1, b: 2, c: function() { return 1; } },
    o2 = { a: 1, b: 2, c: function() { return 1; } };

_.isEqual(o1, o2)
// → false

_.isEqual(_.omit(o1, _.functions(o1)), _.omit(o2, _.functions(o2)));
// → true

functions() function returns a list of function properties, and using omit(),你可以去掉它们。

这是我试过的:

_.isEqual(o1, o2, function(val1, val2) {
  if(_.isFunction(val1) && _.isFunction(val2)) {
    return val1.toString() === val2.toString();
  }
})

Lodash 支持 customizer 函数,允许您编写自己的相等性检查。这似乎是一个足够好的测试来查看函数是否逐个字符相同。

请尝试 isEqualWith

import { isEqualWith, isFunction } from 'lodash-es'

const o1 = { fn() {} }

const o2 = { fn() {} }

const equal = isEqualWith(o1, o2, (v1, v2) =>
  // if `customizer` returns `undefined`, comparisons are handled by the method instead
  isFunction(v1) && isFunction(v2) ? `${v1}` === `${v2}` : undefined,
)

console.log({ equal }) // { equal: true }