Jeff
Jeff

Reputation: 103

Angular Typescript Map to JSON

How can I use JSON.stringify with a Typescript Map. The presumption is the Map keys are all strings.

In this example, the console output is an empty {}

const myMap = new Map<string, Employee>();
myMap.set('employee1', new Employee());
myMap.set('employee2', new Employee());
myMap.set('employee3', new Employee());

console.log('myMap', JSON.stringify(myMap));

Upvotes: 2

Views: 506

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24406

this way you can stringify the Map value

 JSON.stringify([...myMap])

and if you want to convert the value back to Map

 let obj = JSON.parse(stringifyValue)
 let myMap = new Map();
 for (let k of Object.keys(obj)) {
   myMap.set(k, obj[k]);
 }

check this Converting ES6 Maps to and from JSON

Upvotes: 1

Related Questions