【问题标题】:Filter an array based on a key根据键过滤数组
【发布时间】:2019-09-05 11:23:06
【问题描述】:

我正在尝试使用 Angular 7 进行动态研究。我正在使用多个键从我的 API 中获取一个数组:[ _id => 123, pseudo => "Germain", email => .. ]。 我需要用一个字符串过滤所有结果,但只在我的伪字段上过滤,然后返回所有只有匹配值的数组。

我使用 ngFor 显示我的所有结果,并且我已经使用我找到的教程创建了一个过滤器管道..

这是我的研究部分:

<div *ngFor="let profil of profils | filter : searchText" class="col-md-4">
                <figure class="card card-product">
                    <img class="rounded-circle w-50 mx-auto" src="https://i.ibb.co/PQfsPbH/profil.jpg">
                    <figcaption class="info-wrap">
                        <h4 class="title">{{ profil.pseudo }}</h4>
                        <p class="desc">{{ profil.desc }}</p>
                        <div class="rating-wrap">
                            <div class="label-rating">132 reviews</div>
                        </div>
                    </figcaption>
                    <div class="bottom-wrap">
                        <a [routerLink]="['personnalite', profil._id]" class="btn btn-sm btn-primary float-right">Voir le profil</a>
                    </div>
                </figure>
            </div>

这是我的过滤管道功能:

export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items; 
    searchText = searchText.toLowerCase();
    return items.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}

但这只会过滤像这样的数组:[“pseudo1”,“pseudo2”..] 而不是索引的... 知道如何管理吗?

【问题讨论】:

    标签: angular


    【解决方案1】:
    
    export class FilterPipe implements PipeTransform {
      transform(items: any[], searchText: string): any[] {
        if(!items) return [];
        if(!searchText) return items; 
        searchText = searchText.toLowerCase();
        //updated
        return items.filter( item => item.pseudo.toLowerCase().indexOf(searchText) > -1 ); 
       }
    }
    
    

    它将返回一个包含匹配数组项的数组。

    希望对你有帮助:)

    【讨论】:

    • 非常感谢!我刚刚更新了这部分:item =&gt; item.pseudo.toLowerCase() === searchText item =&gt; item.pseudo.toLowerCase().includes(searchText) 以包含类似的结果!
    • 对不起!我没有得到你。这对你有用吗?
    • @Todarmal 正如 OP 所提到的,您不应该检查该项目是否与要搜索的文本完全相同 - 相反,您应该使用 String 类的 .includes() 方法来自 ES2015 及更高版本:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    • @Edric 我已经更新了代码,以便它将在伪中搜索搜索字符串。如您所见,我使用了indexOf() 而不是includes(),因为它可以在 IE 中使用,而且与后者不同。参考 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    • 我很确定你可以在 Angular 中安全地使用 includes,因为 Angular 会自动在你的 polyfills.ts 中为新项目添加必要的 polyfill。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2022-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多