如何使用$.grep()应用多个筛选器

How to apply multiple filters using $.grep()

本文关键字:筛选 应用 何使用 grep      更新时间:2023-09-26

大家好,我正在使用$.grep()在json对象中制作一个过滤器,问题是有时过滤器是null,我必须测试过滤器是否确实存在。在有更多过滤器的情况下,我如何才能让这个代码变得更好,谢谢。

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;
});

我认为更好的代码是:

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];
        }
}

通过这种方式,您可以在filterBy数组中添加任意数量的过滤器,它将通过所有过滤器。您还可以阅读有关函数组合的内容——您可以将所有的过滤函数组合成一个"超级"过滤器,然后只过滤一次数组(这将使您的代码更加高效)。