如何在lodash中使用includes方法来检查对象是否在集合中?

问题描述:

lodash让我用包含来检查基本数据类型的成员资格:

lodash lets me check for membership of basic data types with includes:

_.includes([1, 2, 3], 2)
> true

但以下方法无效:

But the following doesn't work:

_.includes([{"a": 1}, {"b": 2}], {"b": 2})
> false

这让我感到困惑,因为以下搜索集合的方法看起来很好:

This confuses me because the following methods that search through a collection seem to do just fine:

_.where([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}
_.find([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}

我做错了什么?如何使用包含

What am I doing wrong? How do I check for the membership of an object in a collection with includes ?

编辑:
来检查集合中对象的成员资格问题最初为lodash版本2.4.1,更新为lodash 4.0.0

edit: question was originally for for lodash version 2.4.1, updated for lodash 4.0.0

包含 (以前称为包含 code>和 include )方法通过引用(或者更确切地说,使用 === )比较对象。因为在您的示例中, {b:2} 的两个对象文字表示不同的实例,所以它们不相等。注意:

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

然而,这是可行的,因为只有一个 { b:2}

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

另一方面, 其中 (在v4中已弃用)和 find 方法比较对象的属性,所以它们不需要引用相等。作为包含的替代方法,您可能需要尝试 某些 (也别名为任何):

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true