【问题标题】:How to filter an object array in typescript如何在打字稿中过滤对象数组
【发布时间】:2020-03-22 00:58:31
【问题描述】:

我实现了一个具有自动完成功能的输入字段,它使用材料自动完成。 现在我有一个问题,如何在打字稿中过滤对象数组。

这个对象数组包含键和值。

html 看起来像这样:

<input matInput type="text" [formControl]="locationField" [(ngModel)]="node.field" [name]="node.id"
             [matAutocomplete]="auto" placeholder="Field"/>
<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let field of fields" [value]="field.key">
        {{field.value}}
    </mat-option>
</mat-autocomplete>

现在我需要一个方法,如果我在输入字段中添加新值,它会创建新的 mat-option。

过滤功能如下所示:

private filterField(value: string): string[] {
    const allFields = this.locationFilterFields;
    if (value) {
        this.locationFieldResults = ArrayObject.filter((result) => {
            return searchFieldResult.indexOf(value) !== -1;
        });
    }
}

有什么解决办法吗?

【问题讨论】:

    标签: angular filter autocomplete angular-material


    【解决方案1】:

    由于我不知道您所拥有的 value 的类型,但这是您可以过滤对象数组的方式:-

    var friends= [
       {name: "rachel", drink: "latte"},
       {name: "joey", drink: "latte"},
       {name: "phoebe", drink: "tea"},
       {name: "chandler", drink: "tea"}
    ];
    
       var newFriends=  heroes.filter(function(hero) {
       return friends.drink== "latte";
    });
    

    【讨论】:

      【解决方案2】:

          Object.keys(array_object).filter(key => typeof array_object[key as any] === "number").forEach((tempobjentry)=> {
      //      inspect tempobjentry
          });

      上面的代码 sn-p 过滤键类型为数字的 array_object 条目,forEach 有助于枚举过滤后的条目。您可以更换条件以满足您的要求。希望这可以帮助。更详细的解释也可以参考How do I filter an array with TypeScript in Angular 2?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-10
        • 2021-05-24
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        相关资源
        最近更新 更多