【问题标题】:Kendo ListView - Filter fields from nested JSONKendo ListView - 从嵌套 JSON 中过滤字段
【发布时间】:2016-06-28 16:34:37
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript json kendo-ui


    【解决方案1】:

    我有类似的要求,我使用 parse 函数对嵌套的 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;
      }
    }

    【讨论】:

    • 感谢您的帮助!我采用了您的逻辑,但没有将其放入架构中,而是在选中复选框时调用的函数中使用了它。我会用我的解决方案更新我的帖子,但我会选择你的答案作为最佳答案,因为它帮助我找到了我的解决方案。 :)
    猜你喜欢
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    相关资源
    最近更新 更多