Convert a Map to an Object in JavaScript


Borislav Hadzhiev

Wed Nov 03 20212 min read


Photo by Tamara Bellis

Convert a Map to an Object in JavaScript #

To convert a Map to an object, call the Object.fromEntries() method passing it the Map as a parameter, e.g. const obj = Object.fromEntries(map). The Object.fromEntries method takes an iterable, such as a Map, and returns an object containing the key-value pairs of the iterable.

const map = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // ✅ Convert Map to Object const obj = Object.fromEntries(map); console.log(obj); // 👉️ {name: 'Tom', country: 'Chile'} // ✅ Convert Object to Map const newMap = new Map(Object.entries(obj)); console.log(newMap); // 👉️ {'name' => 'Tom', 'country' => 'Chile'}

We used the Object.fromEntries method to convert a Map to an object.

The only parameter the method takes is an iterable, such as an array or Map, that contains key-value pairs.

Here's an example of using the fromEntries method with an array of key-value pairs instead.

const obj = Object.fromEntries([ ['name', 'Tom'], ['country', 'Chile'], ]); console.log(obj); // 👉️ {name: 'Tom', country: 'Chile'}

The Object.fromEntries takes the two-dimensional array of key-value pairs and converts it to an object, in the same way it handles a Map.

If you need to convert the object back to a Map, you can pass the object to the Object.entries method to get an array of key-value pairs.

const entries = Object.entries({name: 'Tom', country: 'Chile'}); // 👇️ [['name', 'Tom'], ['country', 'Chile']] console.log(entries);

Once you have the array of key-value pairs, pass it to the Map() constructor.

const obj = Object.fromEntries([ ['name', 'Tom'], ['country', 'Chile'], ]); const entries = Object.entries({name: 'Tom', country: 'Chile'}); // 👇️ [['name', 'Tom'], ['country', 'Chile']] console.log(entries); const map1 = new Map(entries); console.log(map1); // 👉️ {'name' => 'Tom', 'country' => 'Chile'}

The Map() constructor takes an iterable whose elements are key-value pairs, so a two dimensional array like the one the Object.entries method returns is perfect.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.