如何迭代对象数组并将值放入过滤器?

时间:2016-04-06 14:46:26

标签: javascript arrays kendo-ui kendo-grid

我正在使用kendo ui网格来显示数据。我能够获得我想在对象数组中使用的过滤器

Object {logic: "and", filters: Array[3]}
filters:Array[3]
0:Object
    field:"CheckDate"
    operator:"gte"
    value:Fri Jan 01 2016 00:00:00 GMT-0500 (Eastern Standard Time)
1:Object
    field:"CheckDate"
    operator:"lte"
    value:Tue Jan 31 2017 00:00:00 GMT-0500 (Eastern Standard Time)

我无法弄清楚如何循环遍历此数组并使用过滤器内部的值来获取kendo网格。过滤器代码如下所示:

   grid.dataSource.filter({
            logic: "and",
            filters: [
            { field: "EmployeeName", operator: "contains", value: val }
        ]
    });

我必须为数组中的每个项目添加一行来应用过滤器。

3 个答案:

答案 0 :(得分:0)

您是否要求for ... in声明?如果订单不重要,我会使用它。

for (var val in yourObject.filters){
   grid.dataSource.filter({
            logic: "and",
            filters: [
            { field: val[0], operator: val[1], value: val[2] }
        ]
    });
};

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

答案 1 :(得分:0)

如果您习惯编写C#或Java代码,Javascript for ... in的行为非常奇怪,因此我更倾向于使用jQuery.each,其行为与我期望的一样。

$.each(yourObject.filters, function(index, element){
   grid.dataSource.filter({
            logic: "and",
            filters: [
                { field: element[0], operator: element[1], value: element[2] }
            ]
    });
});

答案 2 :(得分:0)

对象Object {logic: "and", filters: Array[3]}的结构实际上是kendo数据源期望进行过滤的结果。但是,要手动执行此操作,您可以尝试以下操作,

var generateFilterArray = function (yourFilterObject) {
    var filters = []
    for (var i = 0; i < yourFilterObject.filters.length; i++) {
            filters.push({
                field: yourFilterObject.filters[i].field,
                operator: yourFilterObject.filters[i].operator,
                value: yourFilterObject.filters[i].value
            });            
    }

    return {
        logic: yourFilterObject.logic,
        filters: filters
    };
}

grid.dataSource.filter(generateFilterArray(yourFilterObject))

最后,记住不要在循环中调用grid.dataSource.filter(),因为它会多次调用远程端点,所以总是首先创建过滤器对象然后按上面的方式应用它