2

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));

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.