gpt4 book ai didi

javascript - 在 lodash 速记表达式中使用 'or' 进行过滤

转载 作者:行者123 更新时间:2023-11-30 07:57:01 25 4
gpt4 key购买 nike

假设我有一个集合:

var collection = [{type: 'a'}, {type: 'b'}, {type: 'c'}, {type: 'd'}]​​

如何过滤它以便只保留类型“a”和“b”?我希望做类似的事情:

_filter(collection, ['type', 'a', 'b'])

即使用 _.matchesProperty iteratee 速记来处理多个匹配类型,但它不能那样工作。您知道在不定义自定义函数的情况下实现此目的的任何简单方法吗?

最佳答案

您可以将 _.filter 与函数一起使用以使其更具功能性,但简单的 .filter 也足够了:

ES5:

collection.filter(function (i) {
return i.type === 'a' || i.type === 'b';
});

ES6

collection.filter(i => i.type === 'a' || i.type === 'b')

关于javascript - 在 lodash 速记表达式中使用 'or' 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com