How to Serialize a Map in JavaScript

Serialize a Map in JavaScript

Here are two ways to Serialize a Map in JavaScript.

  1. Using Array.from() and JSON.stringify()
  2. 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.