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

2020/11/12 07:22 · javascript ·  · 0评论

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更新的

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的对象中添加对象numbersentry

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)
// > true

本文地址:http://javascript.askforanswer.com/ruheshiyonglodashzhongdeincludefangfajianchaduixiangshifouzaijihezhong.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!