MichaelE
MichaelE

Reputation: 767

how to get nested api data using nestjs httpservice (axios)

I am using nestjs HttpService.get to retrieve data from the following API:

 getVehicleMake(): Observable<AxiosResponse<any>> {
   return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
                 .pipe(
                       map(response => response.data.Results),
                       map(obj => obj.Make_Name),
                       );
}

The API returns a nested array of objects among other data. I am trying to access an Array of Make_Name property without success. I have tried various observable operators none seems to work. I know I could switch to a Promise...but I want to use observables......any ideas would be much appreciated.

Upvotes: 0

Views: 4676

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70131

If Results is an array, what you need to do to create an array of the Make_Name property is to use array methods on the Results property. You have two ways to do this, given the above.

Option 1: Do everything in a single map function

getVehicleMake(): Observable<AxiosResponse<any>> {
  return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
    .pipe(
      map(response => response.data.Results.map(result => result.Make_Name)
    );
}

Option 2: Use two map functions two separate getting the data and mapping it properly

getVehicleMake(): Observable<AxiosResponse<any>> {
  return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
    .pipe(
      map(response => response.data.Results),
      map((results) => results.map(result => result.Make_Name)
    );
}

Upvotes: 1

Related Questions