首页 > 解决方案 > 数组中的 lodash 过滤器

问题描述

在 lodash 中是否有可能在对象中的数组中进行过滤?

我有一个对象,其中有一个数组。看起来像这样

{
  "id": "1",
  "name": "Test 1",
  "tag": ["blue","red", "yellow"]
},
{
  "id": "2",
  "name": "Test 2",
  "tag": ["red", "yellow"]
},
{
  "id": "3",
  "name": "Test 3",
  "tag": ["green"]
}

我现在想做什么。如果标签是红色,他应该输出 id 为 1 和 2 的对象。标签 = Green 只输出 id 为 3 的对象。依此类推。

我现在尝试使用 lodash 过滤器来解决这个问题。

 const filteredColors = _.filter(colors, function(c) {
  return _.includes(['Test 1', 'Test 2'], c.name);
});
// returns Objects with 2 Entrys = Correct

我可以过滤正常值,但是如何在数组中找到值?

标签: javascriptlodash

解决方案


我已经解决了:

 let filter = _.filter(
  colors,
  _.flow(
    _.property('tag'),
    _.partial(_.intersection, ['red', 'green']),
    _.size,
  ),
);

推荐阅读