【问题标题】:How can I build an array of unique Objects based on an object's property in a Promise in javascript?如何在 javascript 的 Promise 中基于对象的属性构建唯一对象数组?
【发布时间】:2017-06-18 01:37:51
【问题描述】:

我尝试了很多方法,但无法解决这个问题。

我有这段代码:

matches => {
            matches.forEach(match => {
              match.away = this.teamService.getTeam(match._links.awayTeam.href);
              match.home = this.teamService.getTeam(match._links.homeTeam.href);
              match.away.then(away => this.teams.indexOf(away) === -1 ? this.teams.push(away) : console.log("This item already exists"));
              match.home.then(home => this.teams.indexOf(home) === -1 ? this.teams.push(home) : console.log("This item already exists"));
            });
            return matches;
          }

我从 API 中检索了一场比赛的所有比赛列表,每场比赛都有一个主队和客队的链接:

match._links.awayTeam.href

getTeam() 方法返回一个 Promise 团队

getTeam(id: string): Promise<Team> {
    return this.http.get(id)
           .toPromise()
           .then(response => response.json() as Team)
           .catch(this.handleError);
    }

所以我需要建立一系列参与范围内比赛的球队。更具体地说,我需要构建一组独特的团队来确定参加比赛的团队的列表。

不管怎样,我打印的列表是这样的:

<md-list>
    <md-list-item *ngFor="let team of teams">
        <button md-raised-button>{{team.teamName}}</button>
    </md-list-item>
</md-list>

结果是每场比赛的每支球队名单:

Team 1 vs Team 2
Team 2 vs Team 1

结果:

Team 1 
Team 2 
Team 1 
Team 2

我使用的是 Angular 4,我想避免导入更多的库。

我认为这与在比较和构建数组之前解决 forEach 中的承诺有关,但我无法让它工作。有任何想法吗?

【问题讨论】:

  • 好吧,首先,如果我是你,我会将所有 observables 存储在 array(无需订阅)并使用 Observable.forkJoin([...]) 执行一些操作时间(在你的情况下:区分数组中的值)......甚至考虑做一个请求?例如:http://myapi.com?some_key=list_of_href_or_whatever。当然,这些方法中的任何一种都会提高响应时间。实际上(按照您的做法),如果您有 n 个“匹配项”,您将发送 n*2 个请求。

标签: javascript arrays angular


【解决方案1】:

不确定我是否 100% 理解了这个问题,但原生 Array.filter() 方法非常适合查找唯一性。它接受一个返回布尔值的回调,并返回一个新数组,其中包括回调为其返回 true 的每个项目。

const makeTeamFilter = (names = {}) => (team) => {
     names[team.name] = names[team.name] ? names[team.name] + 1 : 1;
     return names[team.name] === 1;
};
teams.filter(makeTeamFilter());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2021-01-02
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多