如何使用 lodash 中的 includes 方法检查对象是否在集合中? [英] How do I use the includes method in lodash to check if an object is in the collection?
问题描述
lodash 让我使用 includes
检查基本数据类型的成员资格:
lodash lets me check for membership of basic data types with includes
:
_.includes([1, 2, 3], 2)
> true
但以下方法不起作用:
_.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}
我做错了什么?如何使用 includes
检查集合中对象的成员资格?
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
推荐答案
includes
(以前称为 contains
和 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
另一方面,where
(已弃用在 v4) 和 find
方法根据对象的属性比较对象,所以他们不需要引用相等.作为 includes
的替代方法,您可能想尝试 some
(也称为 any
):
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
这篇关于如何使用 lodash 中的 includes 方法检查对象是否在集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!