【问题标题】:Filter table data过滤表数据
【发布时间】:2019-11-15 16:21:45
【问题描述】:

我想根据几个条件过滤表格。下面是示例图片

我试过的代码

    this.reportData.filter(it => {
        if (
            it.startTimeFilter.includes(this.startdatefilter) &&
            it.endTimeFilter.includes(this.enddatefilter) &&
            it.status.toLowerCase().includes(this.status)
        ) {
            this.filteredData.push(it);
        }
    });

【问题讨论】:

  • 您希望得到什么答案?更具体并告诉我们:what was the output from current code and what more you want to see
  • 当前代码仅在我选择所有字段时才有效..但我想根据单个字段进行过滤..
  • 查看用户可以提供任何组合,例如状态和浏览器或操作系统和 startdate .. 所以我该如何过滤.. 我也没有任何想法

标签: javascript angular typescript filter datatable


【解决方案1】:

好的,我可以给你一些提示来实现这一点,因为我没有完整的代码。确保this.reportData 永远不会更改,因为我们需要对所有数据进行过滤


 applyFiltering(){
    this.dataToShowOnUI = getFilteredData();
 }

 getFilteredData(): any[]{
    let filteredData = JSON.parse(JSON.stringify(this.reportData));
    if(this.startdatefilter && this.enddatefilter){
      filteredData = filteredData.filter(it => 
            it.startTimeFilter.includes(this.startdatefilter) &&
            it.endTimeFilter.includes(this.enddatefilter) 
      );
    }
    if(this.status){
     filteredData = filteredData.filter(data => data.status.toLowerCase().includes(this.status))
    }
    if(this.operatingSystem){
        filteredData = filteredData.filter(data => data.operatingSystem.toLowerCase().includes(this.operatingSystem))
    }
    // and so on ...
    return filteredData;
 }

【讨论】:

    【解决方案2】:

    我假设 this.reportDatathis.filteredData 是数组。那么filter方法的正确使用方法如下:

    this.filteredData = this.reportData.filter(it => 
        it.startTimeFilter.includes(this.startdatefilter) &&
        it.endTimeFilter.includes(this.enddatefilter) &&
        it.status.toLowerCase().includes(this.status)
    );
    

    基本上,filter的参数应该是一个返回布尔值的函数(它告诉元素是否应该作为结果保留),它返回过滤后的新数组而不修改给定的数组。

    【讨论】:

    • 感谢您的回复 .. 我试过了,但对我来说 return 不起作用,所以我将过滤器值分配给数组然后显示 .. 并且 reportdata 是我为表显示的数组..过滤数据只是一个临时变量。
    • 我给出的代码在所有字段中都可以正常工作..但我想根据单个字段进行过滤。
    • 在这种情况下,假设您不想分配this.startdatefilter,请确保将其设为空字符串""。然后.includes("") 将返回true,你应该得到你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2015-11-20
    • 2013-08-29
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多