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

前端之家收集整理的这篇文章主要介绍了javascript – 如何通过检查多个值来过滤数组/对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在玩数组试图了解更多,因为我最近很喜欢与他们合作.
我得到这种情况,我想搜索一个数组,并将其元素值与包含某些所选过滤器值的另一个数组进行比较.

例如,如果我选择3个过滤器,我以后要在新数组中写入匹配 – 只有匹配所有3个过滤器的匹配.

为了更容易理解,我在http://jsfiddle.net/easwee/x8U4v/36/设置了一个例子

代码是:

  1. var workItems = [
  2. { "id": 2616,"category": ".category-copy .category-beauty .category-fashion"},//this is a match
  3. { "id": 1505,"category": ".category-beauty"},// NOT
  4. { "id": 1500,"category": ".category-beauty .category-fashion"},// NOT
  5. { "id": 692,"category": ".category-stills .category-retouching"},// NOT
  6. { "id": 593,"category": ".category-beauty .category-capture .category-fashion .category-product .category-stills .category-stills-retouching "},// NOT
  7. { "id": 636,"category": ".category-beauty .category-copy .category-fashion"},//this is a match
  8. { "id": 547,"category": ".category-fashion .category-lifestyle .category-stills .category-stills-retouching "},// NOT
  9. { "id": 588,"category": ".category-capture .category-recent-work .category-copy .category-beauty .category-fashion"} //this is a match
  10. ];
  11.  
  12. var filtersArray = [".category-beauty",".category-fashion",".category-copy"];
  13.  
  14. var i;
  15. for (i = 0; i < filtersArray.length; ++i) {
  16. var searchString = filtersArray[i];
  17. console.log('Searching for: ' + searchString);
  18. var filtered = $(workItems).filter(function(){
  19. return this.category.indexOf(searchString);
  20. });
  21. }
  22. console.log('Filtered results: ' + JSON.stringify(filtered,null,4));

我也试过

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

但它只匹配第一个过滤器,只有当它在workItems.category的开头

我已经尝试了许多不同的解决方案,但不能真正使这项工作.我应该使用什么功能来返回所需的结果?

解决方法

您可以使用Array对象的.filter()方法
  1. var filtered = workItems.filter(function(element) {
  2. // Create an array using `.split()` method
  3. var cats = element.category.split(' ');
  4.  
  5. // Filter the returned array based on specified filters
  6. // If the length of the returned filtered array is equal to
  7. // length of the filters array the element should be returned
  8. return cats.filter(function(cat) {
  9. return filtersArray.indexOf(cat) > -1;
  10. }).length === filtersArray.length;
  11. });

http://jsfiddle.net/6RBnB/

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

jQuery版本:

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

猜你在找的JavaScript相关文章