Handling Nested Maps
If your Map contains other Maps as values, you can use a recursive function to convert it to JSON.
Example: In this example, the nestedMap contains a nested Map under the key ‘Address’. The mapToJson function successfully converts this structure into a JSON string, which is printed to the console.
function mapToJson(map) {
const obj = {};
for (const [key, value] of map) {
obj[key] = value instanceof Map ? mapToJson(value) : value;
}
return JSON.stringify(obj);
}
const nestedMap = new Map([
['name', 'Geeks'],
['Address', new Map([
['sector', '136'],
['mobile', '+91-9876543210']
])],
['city', 'noida']
]);
const json = mapToJson(nestedMap);
console.log(json);
Output
{"name":"Geeks","Address":"{\"sector\":\"136\",\"mobile\":\"+91-9876543210\"}","city":"noida"}
How to Convert a Map to JSON String in JavaScript ?
A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript.
However, JSON.stringify() does not directly support Map objects.
Table of Content
- Using Object.fromEntries() Method
- Using Array Spread and Reduce
- Handling Nested Maps
Contact Us