使用Typescript从数组获取唯一的父元素

时间:2019-05-29 14:43:14

标签: arrays angular typescript

我的棱角项目上有以下结构:

export interface Campo {
  id?: number;
  nome?: string;
  tabela?: Tabela;
  campos?: Campo[];
}

export interface Tabela {
  id?: number;
  name?: string
  arquivo?: Arquivo;
}

export interface Arquivo {
  id?: number;
  name?: string;
  tabelas?: Tabela[];
}

即,“ Arquivo”具有许多“ Tabela”,而“ Tabela”具有许多“ Campo”。我订阅了返回所有“ Campo”的服务,并将其保留在“ campos”变量上。该服务返回200多个“ Campos”,与大约10个“ Tabelas”和3个“ Arquivos”相关。

我想返回所有唯一的“ Arquivo”(即全部3个“ Arquivo”)。

当我这样做时:

let arquivos = this.campos
        .map(campo => campo.tabela.arquivo.id)
        .filter((value, index, self) => self.indexOf(value) === index);

返回

  

[1001、1002、1003]

这就是我所有3个“ Arquivo”的ID。但是我不想要ID,我想要“ Arquivo”对象。当我尝试时:

let arquivos = this.campos
        .map(campo => campo.tabela.arquivo)
        .filter((value, index, self) => self.indexOf(value) === index);

它返回200个以上的寄存器,因为我有200个以上的“ Campos”,并且它不知道什么“ Arquivos”是唯一的。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以尝试将唯一的arquivo ID映射到arquivo对象,然后获取值

let arquivos = Object.values(this.campos
  .map(campo => campo.tabela.arquivo)
  .reduce((totals, arquivo) => {
    if (!totals[arquivo.id]) {
      totals[arquivo.id] = arquivo;
    }
    return totals;
  }, {})
);
相关问题