如何根据用户输入即时过滤对象数组?

时间:2019-08-13 10:22:09

标签: angular typescript ionic4

这本来应该很容易,但是老实说,出于某种原因,这让我挠头。 我正在尝试根据用户的输入过滤对象数组。

[{ name: Stan, age: 20, height: 190 },
{ name: Pan, age: 30, height: 180 },
{ name: Dan, age: 28, height: 185 },
{ name: San, age: 20, height: 170 }]

例如,如果用户输入“ S”,则他们将得到“ Stan”和“ San”。 如果他们输入“ St”,则缩小到“ Stan”,依此类推,然后在结果显示时显示它们。

我试图根据第一个字母过滤数组,将其推到第二个数组,然后根据第二个输入过滤第二个数组,但是它没有按预期工作。所以在这一点上,我被困在这个位置。

filterCat() {
    this.cate.filter(cat => {
        if (cat.name.startsWith(this.searchTerm.toUpperCase())) {
            this.tempSearchStore.push(cat);
            console.log('cats', cat);
        }
        // this will show all the cats based on the first letter.
    });
}

这是我的html:

<ion-searchbar animated [(ngModel)]="searchTerm" debounce="1000" 
  (ionChange)="filterCat()" mode="ios">
</ion-searchbar>

2 个答案:

答案 0 :(得分:0)

怎么样:

this.cats = [{name:'Stan', age:20, height:190},
{name:'Pan', age:30, height:180},
{name:'Dan', age:28, height:185},
{name:'San', age:20, height:170}]


function filterCat(searchTerm: string) {
 return this.cats.filter(cat => cat.name.toUpperCase().startsWith(searchTerm.toUpperCase()));
}

console.log('Filter S');
console.log(filterCat('S'));

console.log('Filter Sa');
console.log(filterCat('Sa'));

this.whereverList = filterCat('Sa')

和:

<div *ngFor="let cat in whereverList ">{{cat.name}}</div>

您只需将搜索词传递给函数

答案 1 :(得分:0)

startsWith()方法区分大小写,并且您将searchTerm的每个字母大写,这是条件失败的地方。 您需要执行以下操作:

if (cat.name.startsWith(this.searchTerm.charAt(0).toUpperCase() + 
    this.searchTerm.slice(1))) {

    this.tempSearchStore.push(cat);
    console.log('cats', cat);
}

看看这个

Stackblitz