数组中的lodash过滤器

时间:2018-11-20 11:05:21

标签: javascript 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的对象。Tag =仅使ID为3的对象为绿色。依此类推。

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

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

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

5 个答案:

答案 0 :(得分:2)

不需要lodash,只需检查tag数组includes是否在寻找什么:

const arr = [{
  "id": "1",
  "name": "Test 1",
  "tag": ["blue","red", "yellow"]
},
{
  "id": "2",
  "name": "Test 2",
  "tag": ["red", "yellow"]
},
{
  "id": "3",
  "name": "Test 3",
  "tag": ["green"]
}];
console.log(
  arr.filter(({ tag }) => tag.includes('red'))
);

答案 1 :(得分:0)

我已经解决了:

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

答案 2 :(得分:0)

您可以使用Array.prototype.filter()

  

filter()方法将创建一个新数组,其中包含所有通过提供的功能实现的测试的元素。

Array.prototype.map()

  

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

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

function filteredColors(colorsArr, c){
  return colorsArr.filter(i => i.tag.includes(c)).map(i => ({id: i.id}));
}
console.log(filteredColors(colors, 'red'));
console.log(filteredColors(colors, 'green'));

答案 3 :(得分:0)

将数组转换为String,然后可以检查string是否包含颜色。喜欢。

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

 function findColorId(color){
     return items.filter((d)=> {
         if(String(d.tag).includes(color)){
               return d;
         }
     });
 }

 findColorId('red');

答案 4 :(得分:0)

ES6 相比,在 lodash 中要更长一些。

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

// lodash
const lodash = c => _.filter(data, x => _.includes(x.tag,c))

// ES6
const es6 = c => data.filter(x => x.tag.includes(c))

console.log(lodash('green'))
console.log(es6('green'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

两者的想法都是先使用_.filter / Array.filter然后使用_.includes / Array.includes