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 #

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