Tips for retrieving a specific key/value pair during an Http request in Angular

After making an HTTP call, I received a JSON file with the following data:

[
    {
        "totalConfirmed": 555,
        "mainlandChina": 548,
        "otherLocations": 7,
        "deltaConfirmed": 555,
        "totalRecovered": 0,
        "confirmed": {
            "total": 555,
            "china": 548,
            "outsideChina": 7
        },
        "deaths": {
            "total": 17,
            "china": 17,
            "outsideChina": 0
        },
        "reportDate": "2020-01-22"
    },
    {
        "totalConfirmed": 654,
        "mainlandChina": 643,
        "otherLocations": 11,
        "deltaConfirmed": 99,
        "totalRecovered": 0,
        "confirmed": {
            "total": 654,
            "china": 643,
            "outsideChina": 11
        },
        "deaths": {
            "total": 18,
            "china": 18,
            "outsideChina": 0
        },
        "reportDate": "2020-01-23"
    }
]

My objective is to extract and store the values of

totalConfirmed, deaths, & reportDate
. Therefore, the expected output should look like this:

{ 
   totalConfirmed : [555, 654], 
   deaths: [17, 18], 
   reportDates: ["2020-01-22", "2020-01-23"]
}

Below is the function I implemented in my service.ts:

public filteredData(): Observable<History> {
let dataHistory: History;
return this.httpClient.get(this.hostURL).pipe(
  map(res => {       

    dataHistory.totalConfirmedPerDay.push(res["totalConfirmed"]);
    dataHistory.totalDeathPerDay.push(res["deaths"]["total"]);
    dataHistory.dates.push(res["reportDate"]);
    return dataHistory;
  })
);

}

Here is the interface structure I defined for the History data:

export interface History {
  totalConfirmedPerDay: any[];
  totalDeathPerDay: any[];
  dates: any[any];
}

However, an error is occurring which says:

ERROR TypeError: Cannot read property 'totalConfirmedPerDay' of undefined

Answer №1

To achieve this, you can do the following:

return this.httpClient.get(this.hostURL)
  .pipe(
    map(arr => {
      return arr.map(sub => {
        return {
          totalConfirmed: sub.totalConfirmed,
          totalDeathPerDay: sub.deaths.total,
          dates: sub.reportDate
        };
      });
    })
  )

Next, within the subscription block:

.subscribe(res => {
   let op: History = {
     totalConfirmedPerDay: [],
     totalDeathPerDay: [],
     dates: []
   };
   res.forEach(e => {
     op.totalConfirmedPerDay.push(e.totalConfirmedPerDay);
     op.totalDeathPerDay.push(e.totalDeathPerDay);
     op.dates.push(e.dates);
   });
});

Answer №2

There is a typo error: dataHistory has not been initialized.

public filteredData(): Observable<History> {
  return this.httpClient.get(this.hostURL).pipe(
    map(res => {
      return {
        totalConfirmedPerDay: res.totalConfirmed,
        totalDeathPerDay: res.deaths.total,
        dates: res.reportDate
      };
    })
  );

Answer №3

To utilize the map function, follow these steps:

map((dataArray:any[]) => {   //Exclude the entire array    
   dataArray.map(item=>{  //Include only a summarized version
     const newObj={        //Modify each element in the array
       totalConfirmed:item.totalConfirmed,
       totalDeathPerDay:item.deaths.total,
       date:item.reportDate
     }
     return newObj; 
   )
   return dataArray;
  })

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 policy is rejecting the specified white-listed address in the CORS policy with the .WithOrigins

Despite having white-listed the origin http://localhost:4200/ in Startup.cs, Cors is still rejecting the request. This issue persists when making a GET request to my API and attempting to establish a connection through SignalR. Although I can bypass Cors ...

Implementing dynamic display of div based on dropdown selection in typescript

A solution is needed to display or hide specific div elements based on a dropdown selection using Typescript. Sample HTML file: <select class="browser-default custom-select"> <option selected>single</option> <option value="1"> ...

Utilizing the power of Kendo-Spreadsheet in conjunction with angular 6

I am looking to incorporate Kendo-Spreadsheet with Angular 6. I have come across a few examples demonstrating how to use Kendo-Spreadsheet with AngularJS, but I haven't found any resources for Angular 2+. Does KendoUI support Spreadsheet with Angular ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

How to easily deactivate an input field within a MatFormField in Angular

I've come across similar questions on this topic, but none of the solutions seem to work for me as they rely on either AngularJS or JQuery. Within Angular 5, my goal is to disable the <input> within a <mat-form-field>: test.component.h ...

Inverting the Arrangement of Linear Axis

I am in the process of creating a mobile application that includes a chart feature. I am using Nativescript for Angular along with the nativescirpt-ui-chart plugin. Currently, the chart displays grades ranging from 1 to 5, with 5 appearing at the top and ...

What is causing certain code to be unable to iterate over values in a map in TypeScript?

Exploring various TypeScript idioms showcased in the responses to this Stack Overflow post (Iterating over Typescript Map) on Codepen. Below is my code snippet. class KeyType { style: number; constructor(style) { this.style = style; }; } fu ...

Combine arrays of JSON data within a JSON object using JavaScript

Looking for help with reformatting a JSON response {"result":[["abc","de"],["fgh"],["ij","kl"]]} Interested in transforming the response to: {"result":["abc","de","fgh","ij","kl"]} What's the best way to accomplish this task? ...

Changing the contents of a global array in JavaScript

$(document).ready(function(){ var currArray=null; var group=null; var admin=null; var equipment=null; var student=null; console.log("after get array info"); for(var i=0; i<equipment.length; i++) { console.log("equipment at index after get array info ...

Exploring RouteReuseStrategy in Angular 2

I followed the RouteReuseStrategy advice provided here, but had to make some adjustments. Specifically, I had to modify the handling of routeConfig.path in the shouldAttach method as it was empty and causing issues with caching. My Angular router version i ...

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Is there a way to configure side={THREE.BackSide} using an external .glb file?

As a beginner in Threejs, I am trying to incorporate the use of side="THREE.BackSide" with an external model file named room.glb. My development environment consists of nextjs 13 (with typescript and app directory enabled) along with @react-three ...

What are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Creating a specialized Angular validator that detects null values and returns the associated FormControl

I'm currently working on an Angular Reactive form group that includes a custom validator. My form includes 2 date pickers and I need to ensure that if a user selects a date from one picker, they must also select a date from the other. However, I am en ...

In Internet Explorer, the loading time of an Angular 2 webpack application is being delayed by the presence of excessive ".js.map" files

https://i.stack.imgur.com/sY0tJ.pngEvery time I attempt to launch my Angular 2 webpack application on IE11, it noticeably takes longer to load compared to using Chrome. Upon inspecting the Network tab, I noticed that IE is attempting to fetch multiple fi ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Issue with deactivating child routes function

I'm struggling with the routing setup shown below: { path: "home", children: [{ path: "dashboard", children: [{ path: "user", canDeactivate: [CanWeDeactivateThis] }] }] } Although I have components defined in my routes, ...

Enhancing the Angular Community Library Project

I am currently working on an Angular project version 7.1 and have developed 2 angular libraries that are being used in the project. In order to upgrade my project from version 7.1 to 8.2, I used the following command: ng update @angular/cli@8 @angular/core ...

How can I establish default values for 2 to 3 options in a Dropdownlist?

Is there a way to set two values as default in a dropdown list, and when the page is refreshed, the last two selected values are retained as defaults? Thanks in advance! Visit this link for more information ...