Note: While I am familiar with sorting a regular array of objects using .sort()
, I am facing a challenge with an observable object that I am not accustomed to.
My task involves retrieving a JSON array of objects with a service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MockDataService {
private dataUrl = 'assets/data';
constructor(private http: HttpClient) {}
get(filename: string) {
return this.http.get(`${this.dataUrl}/${filename}`);
}
}
Using this service, we can input a filename of a JSON file and obtain an observable:
import { Component, OnInit } from '@angular/core';
import { MockDataService } from '../../shared/services/mock-data.service';
import { ObservableInput } from 'rxjs';
@Component({
selector: 'app-iconography',
templateUrl: './iconography.component.html'
})
export class IconographyComponent implements OnInit {
pbiMini$ = this.mockdata.get('pbi-mini-names.json');
constructor(private mockdata: MockDataService) {}
ngOnInit() {}
}
However, the challenge lies in the need to sort this data based on one of the object keys, such as "name"
{
"name": "Palette",
"code": "pbi-palette",
"char": ""
},
{
"name": "Shopping tag",
"code": "pbi-shopping-tag",
"char": ""
},
I have researched but haven't found a solution. Previously, when dealing with JSON as a plain array rather than an observable, I successfully utilized
ngOnInit() {
this.pbiMini.sort((a, b) => a.name.localeCompare(b.name));
}
Unfortunately, this approach doesn't work with the current observable. How should I go about it?
Update
In response to a suggestion, I attempted
ngOnInit() {
this.pbiMiniSorted$ = this.pbiMini$.pipe(
map(array => {
return array.sort();
})
);
}
However, this fails to compile with the error: error TS2339: Property 'sort' does not exist on type 'Object'.