Open In App

How to serialize a Map in JavaScript ?

In this article, we will discuss, the serialization of maps in JavaScript. Serialization is the conversion of an object or a data structure to another format that is easily transferrable on the network. In JavaScript, the format suitable for transferring is JSON string. So, we usually call the JSON.stringify() method to convert the data in our preferred format. 

To make the data of Map easily transferrable on the network or storage we have to serialize it. The serialization can be done using JSON.stringify() method. This conversion gives the wrong output as when the map is serialized using this method then it returns an empty object. To solve this problem we will first convert the map to an array and then serialize the array generated from it.



Below are the methods to serialize a Map in Javascript:

Approach 1: Using Array.from() and JSON.stringify() Method

Example: This example implements the above approach.






const map1 = new Map([
    [1, 2],
    [2, 3],
    [4, 5]
]);
   
const arr = Array.from(map1);
const serialized = JSON.stringify(arr);
 
console.log(serialized);

Output
[[1,2],[2,3],[4,5]]

This approach has an issue in that it gives extra brackets([]) because of array implementation. To solve this we will convert the data into an object instead of an array

Approach 2: Using Object.fromEntries() and JSON.stringify() Method

Example: This example implements the above approach.




const map1 = new Map([
    [1, 2],
    [2, 3],
    [4, 5]
]);
   
const obj = Object.fromEntries(map1);
const serialized = JSON.stringify(obj);
 
console.log(serialized);

Output
{"1":2,"2":3,"4":5}

Conclusion: Serializing a map is important because maps do not have inbuilt support for serializing and in some cases, we require serialized data. The choice of the approach depends on the user, if the user wants the data in array form we can follow the first approach, else the data can be converted to object form if JSON format is required.


Article Tags :