How do I use the includes method in lodash to check if an object is in the collection?

前端 未结 3 1231
一整个雨季
一整个雨季 2020-12-23 20:03

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

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

But the following do

3条回答
  •  甜味超标
    2020-12-23 20:28

    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
    

    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
    

    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
    

提交回复
热议问题