Converting Angular HTTP Response from Object of Objects to Array with Interface Typing

After receiving a response, the data is structured as follows:

{
    "0": {
        "name": "Novartis AG",
        "symbol": "NVS",
        "has_intraday": false,
        "has_eod": true,
        "country": null,
        "stock_exchange": {
            "name": "New York Stock Exchange",
            "acronym": "NYSE",
            "mic": "XNYS",
            "country": "USA",
            "country_code": "US",
            "city": "New York",
            "website": "www.nyse.com"
        },
        "stock": {
            "open": 84.845,
            "high": 85.39,
            "low": 84.845,
            "last": 85.33,
            "close": 84.24,
            "volume": 3700,
            "date": "2022-01-27T14:40:00+0000",
            "symbol": "NVS",
            "exchange": "IEXG"
        }
    },

This response consists of multiple nested objects. I have created an interface that defines the structure, like this:

export interface Stock {
  ticker: string;
  name?: string;
  open?: number;
  high?: number;
  low?: number;
  last?: number;
  close?: number;
}

Now, my goal is to transform the singular object observable into an array of Stock type observable in the service call:

getStocks(): Observable<Array<Stock>> {
...
}

I am currently facing challenges in achieving this transformation and would greatly appreciate any assistance!

Answer №1

Utilize the "map" operator in rxjs and the "map" method of an array for your function.

Your function could look something like this:

getStocks(){
   this.httpClient.get("....").pipe(
     map((res:any)=>{
        //res is your object
        
        //iterate over Object.keys(res)
        //will be "0", "1", "2"...

        //for example, res[x] is
        const result=Object.keys(res).map(x=>({
              ticker:res[x].acronym,
              name:res[x].stock_exchange.name,
              open:res[x].stock.open,
              high:res[x].stock.high
              ...other properties...
         }));
        return result;
     })
   )
}

Note that the first map inside the pipe(map(...)) transforms your object into another object - remember to always include a return statement when using map=>{...}.

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

Cross-origin resource sharing (CORS) is preventing access because the origin and allowed origin match

Utilizing Dockerized Ory Kratos and Angular (www folder hosted via nginx for header modifications) on localhost and attempting to run the following code: const headers = { Accept: 'application/json', }; fetch('http://127.0.0.1:4433/self-s ...

`Mapping child routes in Angular using basic components`

I am encountering an issue with Angular 8 routes. The problem lies in the child routes not functioning properly. Here are my defined routes: const routes: Routes = [ { path: 'admin', component: MainComponent, children: [ { path: &apo ...

Unknown type encountered when using v-for with Vue3 item

I'm currently going through a Laravel bootcamp and following along with the tutorial. However, I encountered an error when trying to display the model with VueJS using v-for loop. Here is my code: type ChirpModel = { id: number, message: string, ...

Exploring the weather API integration with Angular 4

I've embarked on a journey to teach myself Angular4 by creating a Weather app. However, I'm facing challenges in connecting the API. Despite consulting various resources, such as: https://medium.com/craft-academy/connecting-an-api-to-an-angular- ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

Safari browser failing to render Angular2 ngFor content

I am facing an issue with my ngFor loop where only the first element's data is loaded upon page refresh. However, when I click on an empty element, the data suddenly appears. This unusual behavior seems to be specific to viewing in Safari browser. How ...

I am facing difficulty transitioning from iframe to the Angular App

I have attempted various solutions from stack overflow to switch to an iframe using ProtractorJS, but none of them have successfully worked for me. I am seeking help from someone who has faced a similar issue and could provide some guidance. The Issue: Wh ...

Steps to access information from Firebase database by providing the currentUserID:

Here is the firebase database and table information: . I am looking to extract data from the 'active' table based on userID. I attempted to do this in my service.ts file. getCurrentUserData(userID){ return new Observable(obs => { ...

You cannot use Angular 5 to send a post request with a token that has been retrieved

Hello, I'm facing an issue with making a post request in Angular 5. The token I retrieve seems correct as it works fine when tested with Postman. Can someone provide me with a hint or suggestion on what could be going wrong? AuthService.ts getProfi ...

What is the best way to manage the 'content' attribute in TSX?

I'm currently developing an application that utilizes schema.org. In the code snippet below, you can see how I've implemented it: <span itemProp="priceCurrency" content="EUR">€</span> According to schema.org do ...

Setting an Observable reference to null within a map operator does not have any impact

I am currently working on developing a generic DataService that includes hateoas implementation. Within this setup, there is a REST API endpoint called /root which provides all the required hateoas links. For instance, { _links : { login : { ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...

Verify whether any errors occurred in any controls within the specified form group

I have a group of controls and I would like any errors that occur to be immediately visible in the template. My .ts file: //... Some stuff export class FormularioFacturaComponent implements OnInit { // .... Some stuff private pcIVA = new Fo ...

Snapshots testing app Expo TypeScript Tabs App.tsx

After setting up an Expo project with Typescript and Tabs, I decided to add unit testing using Jest but ran into some issues. If you want to create a similar setup, check out the instructions here: . Make sure to choose the Typescript with Tabs option whe ...

Using a BehaviorSubject in conjunction with ngIf can rearrange the placement of elements

I am facing an issue with the placement of my HTML tags. Here is a snippet from my service: public showExportCsvModal = new BehaviorSubject<boolean>(false); public showDownloadModal = new BehaviorSubject<boolean>(false); And here is how it loo ...

Is there a way to transfer data from a custom hook to a component seamlessly?

I am facing an issue with a custom hook that passes parameter data along with fetched data to the Settings component. Inside Settings, I have a hook called setData11 in useEffect and I am trying to set the data passed from useTable but encountering an er ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...