在 lodash shorthand 表达式中用 'or' 过滤

Filter with 'or' in lodash shorthand expression

假设我有一个 collection:

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

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

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

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

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

ES5:

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

ES6

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

太好了,把 ryeballar 的建议变成一个答案:

假设我有一个:

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

以下将仅过滤掉 'a' 和 'b' 类型:

_.filter(collection, _.conforms({'type': _.partial(_.includes, ['a', 'b'])}))

不是最漂亮的代码,但我认为胜过 ES5 功能并展示了 _.conforms 的工作原理。正是我要找的!

collection.filter(i => ['a', 'b'].includes(i.type));