Open In App

How to serialize a Map in JavaScript ?

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Using Array.from() and JSON.stringify() Method
  • Using Object.fromEntries() and JSON.stringify() Method

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

  • Create a map and add data to it
  • Convert the map into an array using Array.from() method
  • Use the JSON.stringify() method on this converted array to serialize it.

Example: This example implements the above approach.

Javascript




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.

Javascript




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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads