大佬教程收集整理的这篇文章主要介绍了javascript – 如何通过检查多个值来过滤数组/对象,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,如果我选择3个过滤器,我以后要在新数组中写入匹配 – 只有匹配所有3个过滤器的匹配.
为了更容易理解,我在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);
但它只匹配第一个过滤器,只有当它在workItems.category的开头
我已经尝试了许多不同的解决方案,但不能真正使这项工作.@R_693_10675@用什么功能来返回所需的结果?
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; });
一些像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; });
以上是大佬教程为你收集整理的javascript – 如何通过检查多个值来过滤数组/对象全部内容,希望文章能够帮你解决javascript – 如何通过检查多个值来过滤数组/对象所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。