简体   繁体   中英

How to apply multiple filters using $.grep()

Hi guys i'm making a filter in a json object using $.grep() , the problem is that some times the filter is null and i have to test if the filter exists indeed. How can i make this code better in case of having more filters, thanks.

data.result = $.grep(this.Doutores, function (e, index) {
    if (data.descontos)
        return e.descontos == data.descontos;
});
data.result = $.grep(this.Doutores, function (e, index) {
    if (data.especialidade)
        return e.especialidade == data.especialidade;
});
data.result = $.grep(this.Doutores, function (e, index) {
    if (data.preco)
        return e.preco == data.preco;
});
data.result = $.grep(this.Doutores, function (e, index) {
    if (data.proftipo)
        return e.proftipo == data.proftipo;
});

I think a better code would be:

var filterBy = ['descontos', 'especialidade', 'preco', 'proftipo'];
var doutores = this.Doutores;
filterBy.forEach(function(filter){
    data.result = $.grep(doutores, function (e, index) {
        if (data[filter])
        {
            return e[filter] == data[filter];
        }
}

This way, you can add as many filters as you wish into the filterBy array and it will go through all the filters. You could also read about function composition - you can make all the filter functions into one "mega" filter and then filter the array only once (which will make your code more efficient).

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