How to use Object.fromEntries and JSON.stringify In Javascript
This method involves converting the Map into an array of key-value pairs using Array.from() or spreading (…) the Map, then using Object.fromEntries() to convert this array back into an object, followed by JSON.stringify() to convert the object to JSON.
Syntax
const mapToJson = (map) => {
return JSON.stringify(Object.fromEntries(map));
};
Explanation:
- We create a function mapToJson that takes a Map as an argument.
- Object.fromEntries(map) converts the Map into an array of key-value pairs and then into a plain object.
- JSON.stringify() converts this plain object into a JSON string.
Example: Implementation to show how to convert map to JSON in JavaScript.
const mapToJson = (map) => {
return JSON.stringify(Object.fromEntries(map));
};
const myMap = new Map([
['name', 'Abdullah'],
['age', 21],
['city', 'New York']
]);
const jsonString = mapToJson(myMap);
console.log(jsonString);
Output
{"name":"Abdullah","age":21,"city":"New York"}
How to Convert Map to JSON in JavaScript ?
In JavaScript, when working with data, you might encounter situations where you need to convert a Map object into a JSON format. This can be useful for sending data over the network, storing data in local storage, or interfacing with APIs that expect JSON data.
Converting a Map to JSON means converting each key-value pair from the Map into a JSON object. JavaScript’s built-in JSON object provides methods to perform this conversion efficiently.
Contact Us