【问题标题】:List not filtering correctly is search string is empty列表未正确过滤是搜索字符串为空
【发布时间】:2018-05-01 13:19:23
【问题描述】:

我有一个列表,我试图根据用户输入的内容进行过滤。当用户键入时,它会搜索它正在检查的字符串并比较两者,如果找到字符串,它将对象推送到一个数组,然后显示过滤的对象信息。我遇到的问题是,当搜索字段为空白时,需要显示原始的、未更改的对象数组。相反,我得到的是最后一次成功返回的搜索。

HTML

<input type="text" class="in-line filter" id="searchByName" placeholder="Enter a name" (keyup)="filterByName($event.target.value)" />
<study-results-table [originalArray]="originalArray"></study-results-table>

TS

ngOnInit(){
  originalArray = new Array<any>();
  unfiltered = new Array<any>()
}

filterByName(searchString){
    this.filtered = new Array<any>();           
    _.each(this.originalArray, (result) => {
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        if(patientName.includes(searchString.toLowerCase())){
            this.filtered.push(result);
        }
    })

    if(searchString === ""){
        this.originalArray= this.unfiltered;
    }
    this.originalArray= this.filtered;
}

谁能解释一下如何解决这个问题?

【问题讨论】:

    标签: arrays angularjs typescript lodash


    【解决方案1】:

    为什么不使用数组的filter 函数呢?您可以将代码简化为以下内容:

    filterByName(searchString){
        if(searchString.trim().length==0){
            this.originalArray = this.unfiltered;
            return;
        };
        this.originalArray = this.unfiltered.filter( (result)=>{
            let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
            return (name.includes(searchString.toLowerCase()));
        });
    }
    

    【讨论】:

    • 我在发布问题后立即将其切换为过滤器,但注意到我在删除字符时遇到了另一个问题,那是因为我需要循环遍历不可变数组而不是更改后的数组就像您在答案中显示的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2011-06-28
    相关资源
    最近更新 更多