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

Kendo ListView - Filter fields from nested JSON

本文关键字:过滤 字段 JSON 嵌套 ListView Kendo      更新时间:2023-09-26

我在我的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字段时,我想要过滤数据源。

然而,我不确定如何使这个工作正确。

这是我的DataSource:

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"的复选框,则列表视图中的所有项目都将被隐藏。

----- UPDATE -----

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

我有类似的需求,我使用parse函数对嵌套的JSON数据应用过滤器。查看此线程了解详细信息。

模式看起来像这样。

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