如何使用 lodash 中的 include 方法检查对象是否在集合中?

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 进行了更新


答案 1

include(以前称为 and )方法按引用(或更准确地说,与 ) 比较对象。由于示例中的两个对象文本表示不同的实例,因此它们不相等。通知: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 方法按属性比较对象,因此它们不需要引用相等。作为 的替代方法,您可能需要尝试一些(也称为 别名为):includesany

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

答案 2

补充答案,以下是实现此用法的其他三种方法,而无需使用p.s.w.glodash4.17.5_.includes()

假设你想将一个对象添加到对象数组中,只有当不存在时。entrynumbersentry

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