Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs Map Array in Json Document to new Array type

I am retrieving a document from PouchDB in an Angular Service. The document is retrieved in the following format:

{
"_id":"segments",
"_rev":"1-4f0ed65cde23fe724db13bea1ae3bb13",
"segments":[
    { "name":"Aerospace" },
    { "name":"Auto repair" },
    { "name":"Commercial" },
    { "name":"Education" },
    { "name":"Energy" },
    { "name":"Farm/ranch" },
    { "name":"Furniture" },
    { "name":"Heavy Equipment" },
    { "name":"Hobbyist" },
    { "name":"Infrastructure" },
    { "name":"Luxury/Leisure" },
    { "name":"Military" },
    { "name":"MUP" },
    { "name":"Processing" },
    { "name":"Rail" },
    { "name":"Transportation" }
]}

And I want to map that to a new Array that would look like:

[
  { value: "Aerospace", viewValue: "Aerospace" },
  { value: "Auto Repair", viewValue: "Auto Repair" },
  { value: "Commercial", viewValue: "Commercial" }
  ...
 ]

To accomplish this, I have tried this code in my Service:

getSegments(): Observable<any[]> {
  return from(this.database.get('segments'))
  .pipe(
    map((results) => results.segments)
  );
}

And I transform the array in my Component like this:

segments: SegmentsLookup[] = [];
...
this.lookupDbService.getSegments()
  .subscribe(data => {
    data.forEach(element => {
      this.segments.push({value: element.name, viewValue: element.name});
  });
});

This works but I know there is a way to map this properly back in the Service code. Also, when done this way, the compiler complains about the "results.segments" stating "Property "segments" does not exist on type '{}'.

How do I map the data retrieved to the Array that I need in the Service's "getSegments" method?

like image 350
Eric Avatar asked Nov 29 '22 21:11

Eric


1 Answers

You can do the transformation is 2 steps:

  • pipe/map to extract the segments
  • array/map to convert to the final data type

Please see an example here: https://stackblitz.com/edit/angular-ikb2eg?file=src%2Fapp%2Fapp.component.ts

let transformedData = observableData.pipe(
  map(data => {
    console.log(data, data.segments.length);
    return data.segments.map(element => {
      return { value: element["name"], viewValue: element["name"] };
    });
  })
);

transformedData.subscribe(data => {
  this.mylist = data;
});
like image 168
hamilton.lima Avatar answered Dec 05 '22 12:12

hamilton.lima