Borislav Hadzhiev
Wed Nov 03 2021·1 min read
Photo by Max Nguyen
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.
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.
// 👇️ [['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.
// 👇️ {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.