列表未正确过滤是搜索字符串为空

时间:2017-11-17 17:24:18

标签: arrays angularjs typescript lodash

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

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

任何人都可以解释如何解决这个问题吗?

1 个答案:

答案 0 :(得分: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()));
    });
}