What is the best way to retrieve the data in date-value format from a REST API response?

I'm currently developing a Covid-Tracker application using Angular and an open REST API (here).

My goal is to retrieve the number of confirmed cases from the past 30 days in a specific country. This is an example of the response structure:

https://i.sstatic.net/0suUo.png

Within my Angular project, I am extracting the cases data from the JSON response with the following code:

covid.service.ts

  getHistoricalData(country: string): Observable<any> {
    return this.http.get<any>(`${this.URL}/historical/${country}`);
  }

dashboard.component.ts

  this.covidService.getHistoricalData('poland').subscribe(res => {
      let cases = res.timeline.cases;
      console.log(cases);
  });
  }

The output displayed in the browser's console is as follows:

https://i.sstatic.net/5trnN.png

However, I'm facing a challenge in storing this output as key-value pairs, where the key represents the date and the value signifies the number of cases on that particular day. I attempted using a Map, but I'm unsure how to extract the relevant date and its corresponding value. Any advice on how to achieve this would be greatly appreciated.

Answer №1

To access the keys of an object, you can use Object.keys(your_object) like this:

// Assuming your data is stored in the timeline.cases variable
let data = { "6/19/20": 150, "6/20/20": 250 };
let updatedArray = [];
Object.keys(data).forEach(key => {
    updatedArray.push({date: key, cases: data[key]});
});
console.log(updatedArray)

You can then loop through newArray to retrieve each date and its corresponding cases. I hope this solution is helpful!

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

Implementing CSS Pre-loading in an Angular Application with Webpack and Heroku

My current setup involves an Angular application (v4.0.1) with webpack deployed on Heroku. I have a loading spinner in place to show while the app is loading, and it works well locally. However, when deployed on Heroku, the loading spinner (specifically th ...

The import analysis with the vite plugin encountered an error while trying to resolve the entry for the package "xxx". It is possible that the package's package.json file contains incorrect main/module/exports

Check out my npm package here. Unfortunately, when I try to install it in a project using vite, there seems to be an issue with the build which results in the error mentioned above. Here is the complete error information: Your error message text here... ...

The function type is not as strict as the return type in terms of enforcement

I am working on defining a function type that enforces the return type (Object) to have the exact object properties specified in the return type definition. Despite my efforts, the compiler is not enforcing strict adherence to the returned object properti ...

Issue with Angular 2 Observable causing lack of UI updates post Subscription

My child component consists of a search box where users can input search parameters and click on a search button. When the search button is clicked, it emits a 'search' event to the parent component. The parent component then calls a search servi ...

Adding Objects to a JSON File

Currently, I am working on iterating through several links and storing all the results by incrementing each index and fetching the next page number. //dependencies const jsonfile = require('jsonfile') const _ = require('lodash') ...

The React error message states that there are no shared properties between the 'Component<P, S>' type and the 'ComponentLifeCycle<P, S>' type

Encountering an error when attempting to bundle my React application, here is the issue I am facing: https://i.sstatic.net/g0yRh.png This is the structure of my @types/react/index.d.ts file: class Component<P, S> implements ComponentLifecycle< ...

Encountering an issue during Angular installation, which is resulting in an error message and preventing the

Whenever I attempt to install the Angular CLI using the command below: npm install -g @angular/cli An error message pops up, displaying: rollbackFailedOptional: verb npm-session 1a71d92fb103bc6 I'm puzzled as to why this issue is happening and ho ...

Utilizing dynatable JavaScript to dynamically create a table from JSON data

Hi there, I need some assistance in creating a completely dynamic table using dynatable.js, or any other JavaScript suggestions are also welcome. For reference, here are some interesting jQuery Tables. Currently, I'm utilizing a PHP script to call an ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

Is it possible to generate a type solely based on the properties of a class that inherits from another class which is not publicly accessible?

Suppose I have the following code snippet: class Arachnid { numberOfLegs: number = 8; } export class Spider extends Arachnid { numberOfEyes: number = 2; } Is there a method to create a type that only includes the numberOfEyes property from Spider? ...

Newly added rows do not automatically refresh in Angular's mat-table

(Angular 8) I am working with two components, addgame and home. In the home component, I am displaying all games stored in the database using a REST API. Within the home component, I am calling the game component in a dialog view using Mat-dialog. The i ...

What is the process for importing a local widget file in Angular?

I have a unique widget named employee-widget stored in the Angular application folder as employee-widget.js. Despite following the calling method below, the widget fails to load. Method 1: <div> <h4>Attempting to load the employee widget& ...

Having trouble displaying JSON response in Firefox console with Django

Code Snippet: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http ...

"I am experiencing an issue with the PrimeNG year picker as it is unable

My goal was to set up a simple PrimeNG calendar with just a year picker. I followed the implementation instructions from the documentation: <p-calendar inputId="year" [(ngModel)]="date1" view="year" dateFormat=" ...

angular slickgrid grid date formatting only applies to grid view

this.columnDefinitions = [ { id: 'edit', field: 'id', excludeFromColumnPicker: true, excludeFromGridMenu: true, excludeFromHeaderMenu: true, formatter: Fo ...

Using Typescript to resolve a package from a location other than the default node_modules directory

I am currently delving into typescript and eager to start dabbling in creating packages. Here is the current layout of my project: myProject/ ├── node_modules/ ├── src/ │ ├── app │ ├── index.ts │ ├── packages ...

TypeScript may be throwing an error due to a peculiar object possibly being "null"

In my function, I am checking whether an unknown value resembles a Date object: function looksLikeDate(obj: unknown): obj is { year: unknown; month: unknown; day: unknown } { return ( obj !== null && typeof obj === "object" &a ...

Using settimeout in ASP.NET CORE JSON configuration file

I am encountering a 502.3 error in my ASP.NET Core application [due to long requests]. After looking at answers such as Timeouts with long running ASP.NET MVC Core Controller HTTPPost Method and Request timeout from ASP.NET Core app on IIS, it seems that I ...

Using multiple map functions within an RxJS Pipe is not an effective method

I've encountered an issue while trying to manipulate a GET request from the YouTube Search API using the function below. The initial map operation is intended to extract the items from the response Object. The subsequent map operation is supposed to ...

When testing my POST request online, it functions properly. However, I am facing difficulties in getting it to work in next.js as I keep receiving a 405

I am currently working on establishing a connection to Zoho Creator in order to retrieve some data. After successfully testing the request on and receiving the correct response, I encountered an issue while trying to implement it within a next.js applicat ...