Reputation: 103
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
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