Skip to content
Advertisement

How do you JSON.stringify an ES6 Map?

I’d like to start using ES6 Map instead of JS objects but I’m being held back because I can’t figure out how to JSON.stringify() a Map. My keys are guaranteed to be strings and my values will always be listed. Do I really have to write a wrapper method to serialize?

Advertisement

Answer

Both JSON.stringify and JSON.parse support a second argument. replacer and reviver respectively. With replacer and reviver below it’s possible to add support for native Map object, including deeply nested values

JavaScript
JavaScript

Usage:

JavaScript

Deep nesting with combination of Arrays, Objects and Maps

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement