How to use Array Spread and Reduce In Javascript
We can use a combination of array spread and reduce() to convert the Map to an object, and then stringify it.
Example: This example shows the use of the above-explained approach.
const map = new Map([
['name', 'Geeks'],
['contact', '+91-9876543210'],
['city', 'noida']
]);
const obj = [...map].reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
const json = JSON.stringify(obj);
console.log(json);
Output
{"name":"Geeks","contact":"+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