Michael Dorner
Michael Dorner

Reputation: 20135

How to convert JSON data to a map of custom objects in typescript

For this raw data (originally a JSON file and imported by import * as raw_data from './json_file.json'):

let raw_data: object = {"a": {"name": "Name a", "desc": "Description a"}, "b": {"name": "Name b", "desc": "Description b"} }

I would like to retrieve a map of keys (as strings) and the custom objects of interface AnObject

interface AnObject {
    name: string;
    description: string;
}

in typescript. How can I do that?

I have tried

let myObject: Map<string, AnObject> = raw_data as Map<string, AnObject>;

or

let myObject: Map<string, AnObject> = <Map<string, AnObject>>raw_data

but with small success: The object remains an object and myObject.size is undefined.

Upvotes: 1

Views: 8542

Answers (1)

JeromeBu
JeromeBu

Reputation: 1159

You are trying only type level modifications, but an object is actually different from a Map after transpilation, so you need to create it like this :

let myObject: Map<string, AnObject> = new Map(Object.entries(raw_data));

Upvotes: 5

Related Questions