javascript - Kendo ListView - 从嵌套 JSON 中过滤字段

标签 javascript json kendo-ui

我在 Kendo ListView 中使用以下 JSON 数据:

[
  {
    "Id": 2,
    "Name": "My Name",
    "Address": "123 Sesame Street",
    "City": "My City",
    "State": "MO",
    "ProductTypes": [
      {
        "Id": 2,
        "Name": "Cage Free"
      },
      {
        "Id": 3,
        "Name": "Free-Trade"
      },
      {
        "Id": 4,
        "Name": "GAP"
      },
      {
        "Id": 6,
        "Name": "Grass Fed"
      }
    ]
  }
]

现在这是我的目标/问题。我想在选中复选框时过滤数据源,并且我想要过滤的字段是 ProductTypes.Name 字段。

但是,我不确定如何使其正常工作。

这是我的数据源:

profileDataSource: new kendo.data.DataSource({
    transport: {
        read: {
            url: "/Profile/GetAllProfiles",
            dataType: "json"
        }
    },
    schema: {
        model: {
            fields: {
                Id: { type: "number", editable: false, nullable: true },
                Name: { type: "string" },
                ProductTypes_Name: { type: "string", from: "ProductTypes.Name" }
            }
        }
    }
})

这是我当前尝试过滤的方式,但它不起作用:

$("#profileCertificationsListView").on("click", "input[type=checkbox]", function() {
    viewModel.profileDataSource.filter({
        filters: [
            { field: "ProductTypes_Name", operator: "eq", value: $(this).attr("name") }
        ]
    }
}); 

例如,如果我选中名称为“Cage Free”的复选框,则 ListView 中的所有项目都会隐藏。

----- 更新 -----

在@Suresh-c的帮助下,我已经找到了问题的解决方案

这就是我现在的工作:

$("#profileCertificationsListView").on("click", "input[type=checkbox]", function() {
    var name = $(this).attr("name");
    var list = $("#profileDirectoryListView").data("kendoListView").dataSource.data();
    var filtered = [];
    for (var i = 0; i < list.length; i++) {
        for (var j = 0; j < list[i].ProductTypes.length; j++) {
            if (list[i].ProductTypes[j].Name === name) {
                filtered.push(list[i]);
            }
        }
    }

    $("#profileDirectoryListView").data("kendoListView").dataSource.data(filtered);
});

最佳答案

我有类似的要求,我使用解析函数对嵌套 JSON 数据应用过滤器。检查this thread了解详情。

架构看起来像这样。

schema: {
  parse: function (d) {
    var filtered = [];
    for (var i = 0; i < d.length; i++) {
      for(var j=0; j < d[i].ProductTypes.results.length; j++) {
        if (d[i].ProductTypes.results[j].Name == "Cage Free")
          filtered.push(d[i]);
      }
    }
    return filtered;
  }
}

关于javascript - Kendo ListView - 从嵌套 JSON 中过滤字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081692/

相关文章:

javascript - Kendo UI sortable within a sortable

java - 如何将 Immutables 与公共(public)构造函数一起使用但不序列化为元组样式?

javascript - Kendo Grid 数据项选择在 IE 中不起作用

javascript - 从 Kendo Treeview 中读取选定节点的值?

javascript - 根据另一个下拉选择过滤下拉列表

javascript - 类型错误 : undefined is not an object gotten when using navigation. openDrawer()

javascript - 您可以动态地将局部变量添加到函数中吗?

ios - JSON 和 iPhone TableView

javascript - 从现有对象创建新的 javascript 对象

kendo-ui - 在 Angular 2 中导出多个动态剑道网格的 Excel