Here are two ways to Serialize a Map in JavaScript.
- Using Array.from() and JSON.stringify()
- Using Object.fromEntries() and JSON.stringify()
Method 1: Using Array.from() and JSON.stringify()
To serialize a map in JavaScript, you can use the “Array.from()” method to convert a map to an array and use the JSON.stringify() method.
const main_map = new Map();
main_map.set('a', 1);
main_map.set('b', 2);
main_map.set('c', 3);
const serializedMap = JSON.stringify(Array.from(main_map));
console.log(serializedMap);
Output
[["a",1],["b",2],["c",3]]
Method 2: Using Object.fromEntries() and JSON.stringify()
JavaScript Object.fromEntries() method converts a list of key-value pairs into an object. Provide a Map as an argument to this method, and it will convert the Map into a regular object. This object can then be serialized using the JSON.stringify() method.
const main_map = new Map();
main_map.set('a', 1);
main_map.set('b', 2);
main_map.set('c', 3);
const serializedMap = JSON.stringify(Object.fromEntries(main_map));
console.log(serializedMap);
Output
{"a":1,"b":2,"c":3}
Conclusion
The appropriate approach to use depends on our specific requirements. If you need to maintain the insertion order of the Map and deserialize it back to a Map object later, the first method might be more suitable.
The second approach works well if you just want to store the data in a more readable and common object format.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.