Convert a Map to an Object in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

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 aMap, 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, pass it 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 that Object.entries returns is perfect.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.