使用 underscore.js 比较两个具有未定义值的对象

Comparing two objects with undefined values using underscore.js

使用 underscore.js 我正在尝试将两个对象相互比较,如果它们相同,我想 return true。为此,我使用 _.isEqual().

var a = {0: "2", 1: "11", 2: "1"}
var b = {0: "2", 1: "11", 2: "1"}
_.isEqual(a, b) // returns true

按预期工作。我 运行 遇到的问题是我可能在给定时间没有来自一个对象的所有数据。让我们使用这个例子:

var a = {0: "2", 1: undefined, 2: undefined}
var b = {0: "2", 1: "11", 2: "1"}
_.isEqual(a, b) // returns false

如果比较的某些值未定义,我想要一种方法(显然不使用 ._isEqual)使 return true。有什么想法吗?

这是一个解决方案,首先计算出哪些公共键具有定义的值,然后使用 _.isEqual 进行比较:

var a = {0: "2", 1: undefined, 2: undefined}
var b = {0: "2", 1: "11", 2: "1"}

// helper predicate that returns true if the value passed to it is undefined
var notUndefined = _.negate(_.isUndefined);

// find the common keys that have defined values
var keys = _.intersection(_.keys(_.pick(a,notUndefined)), _.keys(_.pick(b,notUndefined)))

// compare only the common keys
var result = _.isEqual( _.pick(a, keys), _.pick(b, keys) );

注意这仅在您的对象包含基本类型(无嵌套对象或数组)时才有效