Angular - Typescript filter in array

Asked

Viewed 85 times

-4

I have a json from Brazilian cities.

To get all the cities of the state that exist in the idEstate ARRAY with SINGLE item, I do it as follows:

getCidades(idEstado: any): Observable<any> {
    return this.http.get<Cidade[]>('assets/dados/cidades.json')
      .pipe(
        map((cidades: Cidade[]) => cidades.filter(c => c.estado == idEstado))
      );
}

This code does not work if I have more than one state in the idState ARRAY.

How to get me back cities of all states that are in the array?

  • Probably using map((cidades: Cidade[]) => cidades.filter(c => Array.isArray(idEstado) ? idEstado.includes(c.estado) : idEstado == c.estado)), but that question is far from clear.

  • Perfect! This is exactly what I was looking for. It worked correctly, thank you very much and I’m sorry for the lack of clarity in the question, in due course I will try to improve.

1 answer

0

For registration purposes and, who knows, be useful to others, follows the solution as the answer of user140808

  getCidades(idEstado: any): Observable<any> {
    return this.http.get<Cidade[]>('assets/dados/cidades.json')
      .pipe(
        map((cidades: Cidade[]) => cidades.filter(c => Array.isArray(idEstado) ? idEstado.includes(c.estado) : idEstado == c.estado))
      );
  }

In this way, all cities whose states are in the idState array are returned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.