Sometimes, we want to convert Map to JSON object in JavaScript.
In this article, we’ll look at how to convert Map to JSON object in JavaScript.
How to convert Map to JSON object in JavaScript?
To convert Map to JSON object in JavaScript, we use the Object.fromEntries method.
For instance, we write
const map1 = new Map([
["foo", "qux"],
["baz", 100],
]);
const obj = Object.fromEntries(map1);
to create map1 with the Map constructor.
Then we call Object.fromEntries to return an array of key-value pair arrays from map1.
To convert the obj object back to a map, we write
const map2 = new Map(Object.entries(obj));