简体   繁体   中英

How to filter dynamic inputs using grep() function of jQuery

I'm using "grep" function of jQuery to filter the data,the below code sample works fine as the condition is static.

But if "name" and "school" parameter has more than one value how to filter it..?, Consider i receive name & school from multiple checkbox list.Ideally i do not want to hard code

var students = 
[ {'id':1, 'name':'amit', 'school':'st john'},
  {'id':2, 'name':'ankit','school':'st mary'},
  {'id':3, 'name':'john', 'school':'hill school'},
  {'id':4, 'name':'matt', 'school':'st john'}];


jQuery.grep(students,function(student)
 { return  student.name =='john' && student.school=='st.john' });

//something like this is possible?
 { student.name =='john||jack||stella' && student.school=='st.john||st.mary' });

You can do it but not quite the way you're thinking:

var names   = [ 'john', 'jack', 'stella' ];
var schools = [ 'st john', 'st mary' ];
var matches = jQuery.grep(students, function(student) {
    return names.indexOf(student.name)     != -1
        && schools.indexOf(student.school) != -1;
});

So you just need to set up your names and schools arrays based on your dynamic inputs and away you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM