如何通过检查多个值来过滤数组/对象

我正在玩数组试图更多地了解它们,因为我最近倾向于与它们合作。 我得到了这种情况,我想搜索一个数组并将它的元素值与另一个包含某些选定filter值的数组进行比较。

例如,如果我选择3个filter,我想稍后在新数组中写入匹配 – 只有那些匹配所有3个filter的匹配。

为了便于理解,我在http://jsfiddle.net/easwee/x8U4v/36/上设置了一个示例

代码是:

var workItems = [ { "id": 2616, "category": ".category-copy .category-beauty .category-fashion"}, //this is a match { "id": 1505, "category": ".category-beauty"}, // NOT { "id": 1500, "category": ".category-beauty .category-fashion"}, // NOT { "id": 692, "category": ".category-stills .category-retouching"}, // NOT { "id": 593, "category": ".category-beauty .category-capture .category-fashion .category-product .category-stills .category-stills-retouching "}, // NOT { "id": 636, "category": ".category-beauty .category-copy .category-fashion"}, //this is a match { "id": 547, "category": ".category-fashion .category-lifestyle .category-stills .category-stills-retouching "}, // NOT { "id": 588, "category": ".category-capture .category-recent-work .category-copy .category-beauty .category-fashion"} //this is a match ]; var filtersArray = [".category-beauty", ".category-fashion", ".category-copy"]; var i; for (i = 0; i < filtersArray.length; ++i) { var searchString = filtersArray[i]; console.log('Searching for: ' + searchString); var filtered = $(workItems).filter(function(){ return this.category.indexOf(searchString); }); } console.log('Filtered results: ' + JSON.stringify(filtered, null, 4)); 

我也尝试过

 filtered = $.grep(workItems, function(element, index){ return element.category.indexOf(filtersArray[i]); }, true); 

但它只匹配第一个filter,并且仅在它位于workItems.category

我尝试了很多不同的解决方案,但不能真正做到这一点。 我应该使用什么function来返回所需的结果?

您可以使用Array对象的.filter()方法:

 var filtered = workItems.filter(function(element) { // Create an array using `.split()` method var cats = element.category.split(' '); // Filter the returned array based on specified filters // If the length of the returned filtered array is equal to // length of the filters array the element should be returned return cats.filter(function(cat) { return filtersArray.indexOf(cat) > -1; }).length === filtersArray.length; }); 

http://jsfiddle.net/6RBnB/

像IE8这样的旧浏览器不支持Array对象的.filter()方法,如果使用jQuery则可以使用jQuery对象的.filter()方法。

jQuery版本:

 var filtered = $(workItems).filter(function(i, element) { var cats = element.category.split(' '); return $(cats).filter(function(_, cat) { return $.inArray(cat, filtersArray) > -1; }).length === filtersArray.length; }); 

我认为你需要Array.prototype.filter

更多相关信息:

Javascript:如何根据属性过滤对象数组?

你可以使用.filter()和布尔运算符,即&&:

  var find = my_array.filter(function(result) { return result.param1 === "srting1" && result.param2 === 'string2'; }); return find[0]; }