无法在多种条件下过滤数据

时间:2019-06-03 13:55:19

标签: javascript angular

嗨,我从数据库获得了JSON数组,如下结构

[{
Attachments: null
ConstructionTypeID: "c2da0a32-2a07-11e9-9500-90b11c61d394"
ConstructionTypeName: "New"
ContractTypeID: "f7adf340-2a07-11e9-9500-90b11c61d394"
ContractTypeName: "Private"
Description: "ddd"
EndDate: "2019-06-27T18:30:00.000Z"
IssueCount: 0
ModelCount: 1
Name: "Sang"
ProjectAddress: null
ProjectID: "01418e66-85f3-11e9-a8cd-38607725a846"
ProjectSubTypeID: "dccd7be7-2a06-11e9-9500-90b11c61d394"
ProjectSubTypeName: "Retail"
ProjectTypeID: "c7569d2a-2a05-11e9-9500-90b11c61d394"
ProjectTypeName: "Commercial"
RevisionID: "1"
RuleCount: 0
StartDate: "2019-06-02T18:30:00.000Z"
SubProjCount: 0
}]

,并且我有多个过滤器可根据用户要求进行应用。请参见下面提供的屏幕截图。 enter image description here

用户可以在此处更改过滤器文本框和日期范围。因此,基于这两个条件,我必须过滤记录并在视图中显示它们。如果用户清除/更新过滤器文本/日期范围值,则相应的功能应该起作用。如果用户删除两个条件,我必须再次显示所有记录。如果您有任何想法,请提供。预先感谢。 我在下面实现了但没有用。

filterProjectDatas() {
    this.filteredData = [];
    if ('Name' in this.data[0]) {
      this.filteredData = this.data.filter((item: any) => {
        return ((this.filterModal.searchStirng && item.Name.toLowerCase().includes(this.filterModal.searchStirng.toLowerCase())) &&
          (this.filterModal.dateFilter && (new Date(item.StartDate) > this.filterModal.dateFilter[0] && new Date(item.EndDate) < this.filterModal.dateFilter[1])));
      });
    }
    // if ('IssueName' in this.data[0]) {
    // }
    this.filterData.emit(this.filteredData);
  }

1 个答案:

答案 0 :(得分:0)

您可以对每个过滤器的组使用||运算符。仅当searchStirngdateFilter的值为non-falsy时,这将检查第二个条件:

this.filteredData = this.data.filter((item) =>
  (!this.filterModal.searchStirng || item.Name.toLowerCase().includes(this.filterModal.searchStirng.toLowerCase()))
  && (!this.filterModal.dateFilter || (new Date(item.StartDate) > this.filterModal.dateFilter[0] && new Date(item.EndDate) < this.filterModal.dateFilter[1]))
)

如果searchStirng为空或为空,则!searchStirng将返回true,并且将不检查该组中的第二个条件。