Extracting an array from an HTTP response in Angular/Typescript using the map operator or retrieving a specific element

Q1: How can I extract an array of objects from a http response using map in Angular?

Q2: Is there a way to retrieve a specific object from a http response by utilizing map in Angular?

Below are the example URL, sample data, CurrencyAPIResponse, and Currency object for reference.

I have experimented with 2 methods and various alternatives, but none seem to be effective:

Q1: Extract an array of objects from a Map property within the Response object:

get(): Observable<Currency[]> {
    return this.httpClient.get<CurrencyAPIResponse>('https://api.coindesk.com/v1/bpi/currentprice.json')
      .pipe( map( response => Array.from( response.bpi.values())));
}

Q2: Retrieve a specific Currency object from a Response containing a Map property:

getOne(name: string): Observable<Currency> {
    // @ts-ignore
    return this.httpClient.get<CurrencyAPIResponse>('https://api.coindesk.com/v1/bpi/currentprice.json')
      .pipe( map( response => response.bpi.get( name)));
}

Upon accessing the specified url, you will obtain an object with a map structure. The data is as follows:

{
  "time": {
    "updated": "Jun 5, 2022 12:04:00 UTC",
    "updatedISO": "2022-06-05T12:04:00+00:00",
    "updateduk": "Jun 5, 2022 at 13:04 BST"
  },
  "disclaimer": "Some text",
  "chartName": "Bitcoin\"",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "&#36;",
      "rate": "29,698.5140",
      "description": "United States Dollar",
      "rate_float": 29698.514
    },
    "GBP": { ... }, 
    "EUR": { ... }
  }
}

The definition of my type and object is as follows:

Currency:

export class Currency {
  code: string = '';
  symbol: string = '';
  rate: number = 0;
  description: string = '';
  rate_float: number = 0;
}

The CurrencyAPIResponse:

interface CurrencyAPIResponse {
  "time": {
  	"updated": string, // or should this be a date?
    "updatedISO": string,
    "updateduk": string
  },
  "disclaimer": string,
  "chartName": string,
  "bpi": Map<string,Currency>
}

Answer №1

Not specifically using the Angular HttpClient, but rather more focused on Javascript.

In response to Question 1, there are various methods you can employ to convert an Object literal into an Array. For instance, if you wish to extract values and create an array from them, you can utilize Object.values(putYourObjectHere). Alternatively, if you want to extract keys and create an array of them from your original object, you can use Object.keys(putYourObjectHere) and so forth.

Regarding Question 2, you have the option of utilizing Array.prototype.find() as well as other options available in both ES5 and ES6. To learn more about the find() method

Answer №2

To achieve your desired outcome through piping observables, you can follow this approach:

fetchData(): Observable<Currency[]> {
    return this.http.get<CurrencyAPIResponse>('https://api.coindesk.com/v1/bpi/currentprice.json')
  .pipe( 
      pluck('bpi'),
      map(obj => [...Object.values(obj)])
  );
}

If you need only one currency:

fetchOne(name: string): Observable<Currency> {
    return this.fetchData()
  .pipe( 
      map(array => array.find(element => element.code === name))
  );
}

A more efficient approach would be to make the initial HTTP call just once, and then utilize a function to extract individual currencies using

array.find(element => element.code === name)
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Reactive Forms: Implementing Error Display and Red Border Styling

Recently, I've started diving into Angular Reactive Forms and I'm quite impressed by the async validator feature for tasks that involve checking data against a database. The separation of validation rules from the GUI is also very appealing to me ...

What specifications need to be set up for server and client configurations when using a MEAN Stack application?

When preparing to launch a mid-level enterprise application for the MEAN Stack, what specific configurations are required? How should these configurations be implemented with Angular 2/4/5 and NodeJS? ...

Can the Date class be expanded by overloading the constructor method?

In my dataset, there are dates in different formats that Typescript doesn't recognize. To address this issue, I developed a "safeDateParse" function to handle extended conversions and modified the Date.parse() method accordingly. /** Custom overload ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Is there a way for me to define the type of a prop based on the type of another prop?

I'm not entirely certain how to phrase this inquiry, or which terminology to employ, so I'll do my best in presenting it. My intention is to develop a component that functions on an array of elements and triggers a render function for each eleme ...

Troubleshooting CORS: Dealing with 'Access-Control-Allow-Origin' issue in Angular when making HTTP calls with Spring Boot. Learn how to handle

To establish a connection between my angular application and the spring boot server, I am using an angular http call. Additionally, I have integrated a security dependency for the spring boot application. When attempting to access it through the browser, ...

Tips on preventing the copying of .txt and .xml files with the fs-extra.copySync function

Currently, I am working on a small TypeScript assignment and facing an issue that I can't seem to solve. Any guidance or advice on the problem mentioned below would be greatly appreciated. The task at hand involves copying a directory from one locati ...

Webpack and incorporating bespoke scripts

Can someone please help me understand how webpack works? I'm currently working on an Angular 2 project with a webpack starter and I have some JavaScript scripts from AWS (my SDK for API Gateway). These are about 10 JS files that I currently have liste ...

Unit testing in Angular: Using TestBed to mock asynchronous calls from injected services

Unit tests need to be written for the DataService as shown below: @Injectable() export class DataService { constructor(private config: ConfigService, private http: HttpClient) { } ..... someMethod(){ let apiUrl = this.config.get(&ap ...

Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code: import next from 'next'; import express from 'express'; import compression from 'compression'; import bodyParser ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Exploring Angular's Animation Feature for HTML Element Movement

I'm currently using @angular/animations module to animate HTML objects and I want to move an object when a button is clicked. For example: * The object initially has top: 800px, left: 800px * Clicking the 'W' button should move the obje ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

What is the best way to adjust the output size for ngx-webcam?

I am looking to determine the smallest possible size for an image that is captured. From my testing with ngx-webcam, I have found that I can adjust the minimum height of the output image based on the display height of the webcam. Is there a method to set ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Is ngForIn a valid directive in Angular 4?

While attempting to loop over the properties of an object using *ngFor with in, I encountered a challenge. Here is a sample code snippet: @Controller({ selector: 'sample-controller', template: ` <ul> <li *ngFor="let i in o ...

How can I display a route from the starting point to the destination with all markers on a Leaflet map, using latitudes and longitudes from an API in Angular

Let's consider a scenario where we have a single bus with a fixed route, and all the bus stops along that route are marked. How can we achieve this in Angular using Leaflet maps as shown in the following image https://i.stack.imgur.com/GgEPS.png ...

Navigating through JSON data in an Angular application

I am currently facing an issue with uploading and parsing a JSON file in my Angular application. The problem lies in the fact that even though I can successfully upload the file, I am unable to access the data from it. To ensure the correct file is being ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...