Convert an Object to a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 in each nested array is the key and the second is the value.

We then passed the result to the Map() constructor.

index.js
const obj = { id: 1, name: 'Fred', }; const map1 = new Map(Object.entries(obj)); console.log(map1); // 👉️ {'id' => 1, 'name' => 'Fred'}
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, use the Object.fromEntries method.

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 and transforms it to an object. The iterable must contain key-value pairs.

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.