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": 2})
> {"b": 2}
我做错了什么?如何使用includes
检查集合中对象的成员资格?
编辑: 问题最初是针对lodash版本2.4.1,更新为lodash 4.0.0
答案 0 :(得分:171)
includes
(以前称为contains
和include
)方法通过引用(或更准确地说,使用===
)比较对象。因为示例中{"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
答案 1 :(得分:6)
通过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
答案 2 :(得分:0)
您可以使用find
来解决问题
const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}
find(data, item)
// > true