【问题标题】:Remove duplicate values from view - Angular从视图中删除重复值 - Angular
【发布时间】:2019-12-26 22:19:20
【问题描述】:

下面是我想要过滤的重复字段,只显示一个而不是两个:

“发布日期”:[ {"certification":"PG-13","iso_639_1":"","note":"Telluride Film Festival","re​​lease_date":"2018-08-31T00:00:00.000Z ","类型":1},

{"certification":"PG-13","iso_639_1":"","note":"","re​​lease_date":"2018-09-28T00:00:00.000Z ","type":2}]}]}

下面的组件显示来自上面 json 的两条记录:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css']
})
export class MovieComponent implements OnInit {
  movie: Object;
  certification: Array<Object>;
  video: Object;
  constructor(
    private _moviesServices: MoviesService,
    private router: ActivatedRoute
  ) {

  }

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this._moviesServices.getMovie(id).subscribe(movie => {
        this.movie = movie;
      });
      this._moviesServices.getCertification(id).subscribe((res: any) => {
        const usCertifications = res.results.filter((result: any) => {
          return result.iso_3166_1 === "US";
          // return this.certification === result.certificationAll;
        });
        this.certification = usCertifications;
      });

    })

  }

}

html:

<div class="mr-3" *ngIf="certification"><span *ngFor="let cert of certification">
          <span *ngFor="let release of cert.release_dates">
            <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}</span>
          </span>
        </span>
      </div>

【问题讨论】:

  • 这两个不是重复值。它们不一样。一个有note,另一个没有,发布日期也不一样。那么应该根据什么来过滤它们呢?
  • 您最初从getCertification 得到的实际回复是什么,您可以添加一个示例吗?
  • 是的,我尝试按注意过滤,但有些地方不可用。

标签: angular angular6 angular7 angular8 themoviedb-api


【解决方案1】:

您可以添加一个函数来删除组件中的重复项或使用管道来执行相同的操作 类似的东西

result:any=[];
removeDuplicates(): any{
   this.certification.forEach((item)=>{
        if(this.result.indexOf(item) < 0) {
            this.result.push(item);
        }
   });
return this.result;
} 

然后在模板中调用它

<div class="mr-3" *ngIf="certification"><span *ngFor="let cert of removeDuplicates(certification)">
          <span *ngFor="let release of cert.release_dates">
            <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}</span>
          </span>
        </span>
      </div>

【讨论】:

  • @user8351493 我已经添加了完整的组件代码并尝试过,但出现了一些错误
  • 错误是什么?我在 forEach 中编辑了函数以使用arrowNotation。试试看是否可行
  • 我刚刚在 ngOnInit() 之后添加了该函数,并再次添加了您的更新,但得到了相同的重复项。添加arrowNotation后没有错误但同样重复PG-13两次
【解决方案2】:

假设您想根据certification 属性过滤掉重复项,因此我们可以使用filter() 来执行此操作。如果不是那个属性,只需在下面的代码中更改要过滤的属性。另外,我假设从您得到的原始响应中,您只需要一个对象(美国证书),因此无需使用filter() 创建一个数组,而是使用find()。这样我们只能得到一个对象。所以我建议如下:

certifications = [];

// ...

this._moviesServices.getCertification(id).subscribe((res: any) => {
  const uscerts = this.results.find((result: any) => (result.iso_3166_1 === "US"));

  if (uscerts && uscerts.release_dates && uscerts.release_dates.length) {
    this.certifications = uscerts.release_dates.filter((item, i, arr) =>
      // filter by what prop you want, here we use certification
      arr.findIndex((x) => (x.certification === item.certification)) === i);
  } else {
    this.certifications = [];
  }
});

现在您可以迭代 this.certifications 中的数组:

<span *ngFor="let release of certifications">
  {{release.certification}}
</span>

DEMO: StackBlitz

另外,我建议您实际使用数据模型,而不是使用any。如果您尝试做错事,IDE 可以警告您,让您的生活变得如此轻松;)

【讨论】:

  • 感谢您的帮助,我认为这是解决此问题的最简单解决方案。我刚刚添加了 ngIf 以防万一它应该限制徽章(设计师 ui 徽章)出现在视图中。是的,我将使用该模型。目前正在努力从 angularjs 迁移到最新版本。 :)
【解决方案3】:

您可以编写一个管道,其中包含数组并返回非重复项。

@Pipe({ name: 'duplicate' })
export class DuplicatePipe implements PipeTransform {
  transform(elements: any[]) {
     let result = [];
     elements.forEach(element => {
      if (!elements.find(fEle => fEle.certification === element.certification)) {
        result.push(element);
      }
    });
  return result;
  }
}

在模板中:

<div class="mr-3" *ngIf="certification"><span *ngFor="let cert of certification">
          <span *ngFor="let release of cert.release_dates | duplicate">
            <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}</span>
          </span>
        </span>
</div>

【讨论】:

    【解决方案4】:

    我假设您只想删除基于 certification 属性的重复项。

    组件:

    在你的组件下面添加removeDuplicates()函数。

    我们正在使用 JavaScript Map 对象来跟踪重复项。

    removeDuplicates(certification): any {
        certification.forEach((item) => {
          var filteredResults = new Map();
    
          item['release_dates'].forEach((value) => {
            if (!filteredResults.has(value.certification)) {
              filteredResults.set(value.certification, value);
            }
          });
    
          item['release_dates'] = [];
    
          filteredResults.forEach((value, key) => {
            item['release_dates'].push(value);
          });
        });
    
        return certification;
      }
    

    HTML:

    在你的 HTML 中调用removeDuplicates() 函数中的*ngFor 如下所示。

    <div class="mr-3" *ngIf="certification">
        <span *ngFor="let cert of removeDuplicates(certification)">
        <span *ngFor="let release of cert.release_dates">
          <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}<br></span>
        </span>
      </span>
    </div>
    

    你可以在 StackBlitz 上看到它的直播:https://stackblitz.com/edit/angular-4yklwe

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 2016-12-13
      • 2013-04-20
      • 1970-01-01
      • 2014-03-25
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多