Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get object when sorting an Observable array

I can’t get an object when I try to sort an Observable Array.

I want to sort it by "Localite" and the result I obtain is only "Localite" and no more the complete object.

I don’t understand why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My Json file looks like this :


{
    A[
       Code_Postal: ...
       Localite: ...
       Sous_commune: ...
       Commune_principale: ...
     ]
    B[
      Code_Postal: ...
      Localite: ...
      Sous_commune: ...
      Commune_principale: ...
     ]
    C[
      ...
     ]
    ...
}

My interface is like :


export interface Communes{
    Code_Postal       : number;
    Localite          : string;
    Sous_commune      : string;
    Commune_principale: string;
}

The function who sort the json file looks like this :


getCommunes(prov: string): Observable<Communes[]> {
    return this.jsonService.getData(this.zipCodesFile)
      .pipe(
        map((response: any) =>
          response[prov].map((localite: Communes) => localite.Localite)
            .sort((a: any, b: any) => {
              return a.localeCompare(b, 'en', { sensitivity: 'base' });
            })
        ),
      )
  }

The calling of the function in TS file is like this :


  loadCommunes(): void{
  this.communes$ =  this.apiService.getCommunes('Anvers');
  }

In the html file I want be able to use it like this :


  <ul>
  <li *ngFor="let commune of (communes$ | async)">{{commune.Code_Postal}} - {{commune.Localite}}</li>
</ul>

How can I retrieve an object after sorting of the json file?

Thanks

>Solution :

change your map to:

    map((response: any) =>
      response[prov]
        .sort((a: Communes, b: Communes) => {
          return a.Localite.localeCompare(b.Localite, 'en', { sensitivity: 'base' });
        })
    ),

the array map you had on there is changing it into an array of the Localite value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading