Javascript 如何使用lodash中的includes方法检查对象是否在集合中?
lodash允许我使用Javascript 如何使用lodash中的includes方法检查对象是否在集合中?,javascript,functional-programming,lodash,Javascript,Functional Programming,Lodash,lodash允许我使用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":
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}
我做错了什么?如何在包含的集合中检查对象的成员身份
编辑:
这个问题最初是针对lodash版本2.4.1提出的,后来针对lodash 4.0.0更新了(以前称为包含和包含)方法通过引用比较对象(或者更准确地说,使用==
)。因为在您的示例中,{“b”:2}
的两个对象文本代表不同的实例,所以它们并不相等。注意:
({"b": 2} === {"b": 2})
> false
但是,这将起作用,因为只有一个{“b”:2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
另一方面,(在v4中不推荐使用)和方法根据对象的属性比较对象,因此它们不需要引用相等。作为包含
的替代方案,您可能希望尝试(别名为any
):
通过p.s.w.g
补充答案,以下是使用lodash
4.17.5
,而不使用\uu.includes()实现此目的的其他三种方法:
假设您要将对象条目
添加到对象数组数字
,前提是条目
不存在
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}]
如果要返回布尔值
,在第一种情况下,可以检查正在返回的索引:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
您可以使用find
来解决您的问题
已在lodash v4-使用中删除了\uu0.contains
instead@BillyMoon呜呜!没错,lodash v4.0.0(2016-01-12发布)删除了包含的别名。我会更新这个
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}
find(data, item)
// > true