isADon
isADon

Reputation: 3673

Angular Get JSON as Map

I have following JSON structure

{
"2019-03-27T21:00":23,
"2019-03-27T21:30":13,
"2019-03-27T21:48":20,
"2019-03-27T20:42":16
}

I would like to get this to a Typescript Map<Date, number>

I have tried declaring the map in my http call

this.http.get<Map<Date, number>>

Unfortunately this does not give me a map and calling response.values() is undefined on values()

How can I get my Json to a Map<Date, number>

Upvotes: 0

Views: 61

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Saying that your response is of type Map<Date, number> won't typecast the data you receive, its just for Typescript intellisense that you are saying that the response is of type Map<Date, number> but your actual response is still the same.

Do this instead:

this.http.get<Map<Date, number>>(url).pipe(map(data) => {
    return new Map(Object.entries(data))
})

Upvotes: 3

Related Questions