Using Typescript for-loop to extract information from a JSON array

I'm currently developing a project in Angular 8 that involves utilizing an API with a JSON Array. Here is a snippet of the data:

   "success":true,
   "data":{
      "summary":{
         "total":606,
         "confirmedCasesIndian":563,
         "confirmedCasesForeign":43,
         "discharged":43,
         "deaths":10,
         "confirmedButLocationUnidentified":0
      },
      "regional":[
         {
            "loc":"Andhra Pradesh",
            "confirmedCasesIndian":9,
            "confirmedCasesForeign":0,
            "discharged":1,
            "deaths":0
         },
         {
            "loc":"Bihar",
            "confirmedCasesIndian":4,
            "confirmedCasesForeign":0,
            "discharged":0,
            "deaths":1
         },
         {
            "loc":"Chhattisgarh",
            "confirmedCasesIndian":1,
            "confirmedCasesForeign":0,
            "discharged":0,
            "deaths":0
         },
         {
            "loc":"Delhi",
            "confirmedCasesIndian":30,
            "confirmedCasesForeign":1,
            "discharged":6,
            "deaths":1
         }
      ]
   },
   "lastRefreshed":"2020-03-26T04:18:02.528Z",
   "lastOriginUpdate":"2020-03-25T13:15:00.000Z"
}

component.ts



  constructor(private _IndiaApiService: IndiaApiService) { }

  info:IndiaClass[]
  regional:[];

  ngOnInit() {
    this._IndiaApiService.getIndiaData()
    .subscribe
    (
      data=>
      {
        this.info = data;
      }
    )
  }

 

component.html

<table border=1>
            <tr>
                <th>State</th>
                <th>Recovered cases</th>
            </tr>

            <div *ngFor="let item of info.data.regional">
              <tr>
                  <td>{{ item.loc }}</td>
                  <td>{{ item.discharged }}</td>
              </tr>
            </div>
</table>

The code above displays a table with data from the first element of the array, but now I need to iterate through all 25 elements using *ngFor directive. How can I achieve this efficiently? Any alternative methods are also welcome. Thank you.

Answer №1

I am having a bit of trouble grasping exactly what you are seeking. However, perhaps you could experiment with this suggestion

<div *ngFor="let item of data.items">
  <p>{{ item.name }}</p>
  <p>{{ item.quantity }}</p>
</div>

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

Transferring information among components and incorporating the ngDoCheck function

We are currently working on transferring data from one component to another using the following method. If there is no data available, we display an error message; however, if there is data present, we populate it in a select box. showGlobalError = true; ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Connecting attribute in Angular 5 through @Input

(UPDATED) I originally had a basic jarallax setup with just a div containing the corresponding configuration in a component: <div class="view cover-jarallax" data-jarallax="{"speed": '0.w'}" style="background-image: url(imgurl);' + &apo ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

How to dynamically assign tab indices in Angular's mat-tab-group using ngFor

In my angular web application, I have a tab group that requires a mandatory tab (for posting a new object) and dynamic tabs (for editing existing objects). I am looking to set specific tabindex values for the dynamic tabs in order to have one of them disp ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

Executing Timers in Angular 5 Service

I am working on implementing a property called currentAndLastVehicles in my service that needs to be updated automatically every second. Here is what I have so far: import { Injectable } from '@angular/core'; @Injectable() export class SharedD ...

Using PHP encryption and decrypting with AES in Angular using Crypto-JS

I have successfully implemented encryption and decryption in PHP using aes-256-cbc. However, I am now facing a challenge in decrypting the same content in Angular 7. Encryption in php using aes-256-cbc by following method $this->data ="plaintext&qu ...

Angular - Reacting to dynamically rendered content post-navigation

I am working on an angular application that consists of various components and pages where users can create and view html content. Once the content is fully loaded, I need to search for specific elements and add an onclick event to them. My initial approa ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Troubleshooting TypeScript: Issues with Object.assign and inheritance

After successfully using the code within an Angular project, I decided to switch to React only to find that the code is now producing unexpected results. class A { constructor(...parts: Partial<A>[]) { Object.assign(this, ...parts); } } cla ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

Is there a way for me to determine when a user has signed in for the first time?

Issue at Hand I am facing an obstacle in detecting when a user initially connects to Google on my app using Firebase. The method I am currently utilizing is auth.signInWithPopup(googleProvider);. To address this query, I delved into the documentation and ...

The error "commands.reduce is not a function" is encountered when using the router.navigate function in

When I try to send a string as a link to my router, such as "/blog/pages/3", I encounter the error "commands.reduce is not a function". Surprisingly, despite the error message showing up in the console, the navigation still works. goToPage(link) { this ...