How to useObject.fromEntries() and JSON.stringify() Method in Javascript

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.



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:

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

Similar Reads

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....

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

...