如何使用 loash 中的 include 方法来检查一个对象是否在集合中?

Loash 允许我使用 includes检查基本数据类型的成员资格:

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

但是下面的方法不起作用:

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

这让我感到困惑,因为下面这些搜索集合的方法似乎效果不错:

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

我做错了什么?如何使用 includes检查集合中对象的成员资格?

编辑: 这个问题最初是针对 lodash2.4.1版本的,后来更新为 lodash4.0.0版本

324475 次浏览

includes(以前称为 containsinclude)方法通过引用(或者更准确地说,通过 ===)比较对象。因为示例中 {"b": 2}的两个对象文本表示 与众不同实例,所以它们不相等。注意:

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

然而,这将工作,因为只有一个 {"b": 2}实例:

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

另一方面,where(在 v4中弃用)和 find方法根据对象的属性比较对象,因此它们不需要引用相等性。作为 includes的替代品,您可能想尝试 some(也别名为 any) :

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

作为对 p.s.w.g答案的补充,以下是使用 lodash 4.17.5没有使用 _.includes()实现这一目标的其他三种方法:

假设您想要将一个对象 entry添加到对象 numbers的数组中,只有在 entry还不存在的情况下才需要这样做。

let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];


let entry = { to: 1, from: 2 };


/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0




/*
* 2. This will return the entry that matches. Even if the entry exists
*    multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}




/*
* 3. This will return an array of objects containing all the matches.
*    If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]

如果要返回 Boolean,在第一种情况下,可以检查正在返回的索引:

_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true

你可以用 find来解决你的问题

Https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}




find(data, item)
// (*): Returns the matched element, else undefined.