Categories
JavaScript Answers

How to convert Map to JSON object in JavaScript?

Spread the love

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));

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *