Convert an Object to a Map in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20211 min read

banner

Photo by Max Nguyen

Convert an Object to a Map in JavaScript #

To convert an object to a Map, call the Object.entries() method to get an array of key-value pairs and pass the result to the Map() constructor, e.g. const map = new Map(Object.entries(obj)). The new Map will contain all of the object's key-value pairs.

index.js
const obj = { id: 1, name: 'Fred', }; // โœ… Convert Object to Map const map1 = new Map(Object.entries(obj)); console.log(map1); // ๐Ÿ‘‰๏ธ {'id' => 1, 'name' => 'Fred'} // โœ… Convert Map to Object const objAgain = Object.fromEntries(map1); console.log(objAgain); // ๐Ÿ‘‰๏ธ {id: 1, name: 'Fred'}

We used the Object.entries method to get an array of key value pairs.

index.js
// ๐Ÿ‘‡๏ธ [['id', 1], ['name', 'Fred']] console.log(Object.entries({id: 1, name: 'Fred'}));

The first element of each nested array is the key and the second - the value.

We passed the result to the Map() constructor. The Map constructor takes an iterable such as an array of key-value pairs and creates a Map.

If you need to convert the Map back to an object, you can use the Object.fromEntries method to transform the array of key-value pairs into an object.

index.js
// ๐Ÿ‘‡๏ธ {id: 1, name: 'Fred'} console.log( Object.fromEntries([ ['id', 1], ['name', 'Fred'], ]), );

The Object.fromEntries() method takes an iterable, such as a Map or an array as a parameter. The iterable must contain key-value pairs.

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