簡體   English   中英

使用Typescript從數組獲取唯一的父元素

[英]Get unique parent elements from array using 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”是唯一的。

我怎樣才能做到這一點?

您可以嘗試將唯一的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;
  }, {})
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM