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

189

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


8
_.contains在lodash v4中已被移除 - 请使用_.includes代替。 - Billy Moon
@BillyMoon 哎呀!是的,你说得对,lodash v4.0.0(发布于2016年01月12日)删除了contains别名。我会更新这个。 - Conrad.Dean
3个回答

285

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

17

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

4
你可以使用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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接