0

I have this structure on my angular project:

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[];
}

i.e., An "Arquivo" has many "Tabela", and "Tabela" has many "Campo". I subscribe on a service that return all "Campo" and I keep it on "campos" variable. This service return more than 200 "Campos", associated with about 10 "Tabelas" and only 3 "Arquivos".

I want to return all unique "Arquivo" (i.e. all 3 "Arquivo").

When I do:

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

It returns

[1001, 1002, 1003]

So it is the ids of all 3 "Arquivo" that I have. But I dont want the ids, I want the "Arquivo" objects. When I try:

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

It returns more than 200 registers, because I have more than 200 "Campos" and it can't know what "Arquivos" is unique or not.

How can I do that?

2
  • 1
    I'd recommend building an object whose keys are the arquivo ids and whose values are the arquivo objects, and then returning just the values of that object. This lets you easily avoid duplicates without searching through an array over and over. Commented May 29, 2019 at 15:23
  • 1
    No, that’s okay. Thanks for offering. Commented May 29, 2019 at 17:24

1 Answer 1

1

You could try mapping the unique arquivo ids to the arquivo objects, and then, get the values

let arquivos = Object.values(this.campos
  .map(campo => campo.tabela.arquivo)
  .reduce((totals, arquivo) => {
    if (!totals[arquivo.id]) {
      totals[arquivo.id] = arquivo;
    }
    return totals;
  }, {})
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Alberto. But it returns to me an array with just the data of 1 "Arquivo".
Sorry I mixed up the reduce arguments. Try it again @aseolin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.