如何获取*ngFor循环唯一记录

Ayy*_*yan 4 javascript angular

如何从此数组中获取唯一记录.我需要{{ subitem.author }}从这一系列项目中获得独特性.

<div *ngFor="let item of items">   
    <ion-list *ngFor="let subitem of item.items" (click)="authorquotes(subitem.author);">
        <ion-item >
            {{ subitem.author }} 
        </ion-item>
    </ion-list>
</div> 
Run Code Online (Sandbox Code Playgroud)

在具有多个记录的数组中.从那个数组中,我需要过滤独特的作者.

Hri*_*mov 10

您必须创建一个使用唯一项过滤数组的管道:

@Pipe({
  name: 'filterUnique',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    // Remove the duplicate elements
    let uniqueArray = value.filter(function (el, index, array) { 
      return array.indexOf (el) == index;
    });

    return uniqueArray;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以应用你的管道:

<div *ngFor="let item of items | filterUnique">   
    <ion-list *ngFor="let subitem of item.items" (click)="authorquotes(subitem.author);">
        <ion-item >
            {{ subitem.author }} 
        </ion-item>
    </ion-list>
</div>
Run Code Online (Sandbox Code Playgroud)

工作演示:https://plnkr.co/edit/yxvoKVD3Nvgz0T3AB7w3?p = preview

  • 您可以使用 ES6 Set http://stackoverflow.com/a/33121880/6806381,而不是使用 `filter` 和 `indexOf` (3认同)