基于其他数组过滤集合(对象数组) [英] Filter collection (array of objects) based on other array

查看:190
本文介绍了基于其他数组过滤集合(对象数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题。我喜欢根据fruits数组过滤这个fruitsCollection。
我希望结果是,例如:

I have the following problem. I wolud like to filter this fruitsCollection based on fruits array. I would like to be the result was that, for example :

     filteredFruits1 [ all fruits with the 
                       exception of those which are in  
                       fruitsToCut array
                     ]

示例:

var fruitsToCut = [ 'egzotic', 'other'],
    fruitsCollection = [ {name: papaya, type: 'egzotic'}, 
                         {name: orange, type: 'citrus'}, 
                         {name: lemon, type: 'citrus'}
                       ]

也许有一些下划线功能?

Maybe some underscore function?

推荐答案

在现代浏览器上,您可以使用原生 filter

On a modern browser, you can use the native filter:

fruitsCollection.filter(function(fruit) {
  return fruitsToCut.indexOf(fruit.type) === -1;
} );

否则,您可以使用下划线过滤器的方式几乎相同:

Otherwise, you can use the underscore filter in pretty much the same way:

_.filter( fruitsCollection, function(fruit) {
  return !_.contains(fruitsToCut, fruit.type);
} );

此外,您的水果名称需要引用:

Also, your fruit names need to be quoted:

fruitsCollection = [ {name: 'papaya', type: 'egzotic'}, 
                         {name: 'orange', type: 'citrus'}, 
                         {name: 'lemon', type: 'citrus'}
                       ];

这篇关于基于其他数组过滤集合(对象数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆