Convert a Map to an Object in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

banner

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee