Last updated: Mar 4, 2024
Reading timeยท2 min
To convert a Map
to an object, call the Object.fromEntries()
method
passing it the Map
as a parameter.
The Object.fromEntries
method takes an iterable, such as a Map
, and
returns an object containing the key-value pairs of the iterable.
const map = new Map([ ['name', 'Bobby'], ['country', 'Chile'], ]); // โ Convert Map to Object const obj = Object.fromEntries(map); console.log(obj); // ๐๏ธ {name: 'Bobby', country: 'Chile'} // โ Convert Object to Map const newMap = new Map(Object.entries(obj)); console.log(newMap); // ๐๏ธ {'name' => 'Bobby', 'country' => 'Chile'}
The
Object.fromEntries()
method takes an array of key-value pairs or a Map
object and converts the
value to an object
Here's an example of using the Object.fromEntries()
method with an array of
key-value pairs instead.
const obj = Object.fromEntries([ ['name', 'Bobby'], ['country', 'Chile'], ]); console.log(obj); // ๐๏ธ {name: 'Bobby', country: 'Chile'}
The Object.fromEntries()
method takes a two-dimensional array of key-value
pairs and converts it to an object in the same way it handles a Map
.
Map.forEach()
This is a three-step process:
Map.forEach()
method to iterate over the Map
.const map = new Map([ ['name', 'Bobby'], ['country', 'Chile'], ]); const obj = {}; map.forEach((value, key) => { obj[key] = value; }); // ๐๏ธ { name: 'Bobby', country: 'Chile' } console.log(obj);
The function we passed to the Map.forEach()
method gets called for each key-value pair of the Map
and gets passed the
following parameters:
value
- the value of the iterationkey
- the key of the iterationmap
- the Map
object that's being iteratedOn each iteration, we assign the current key-value pair to the new object.
for...of
This is a three-step process:
for...of
loop to iterate over the Map
.const map = new Map([ ['name', 'Bobby'], ['country', 'Chile'], ]); const obj = {}; for (const [key, value] of map) { obj[key] = value; } // ๐๏ธ { name: 'Bobby', country: 'Chile' } console.log(obj);
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
On each iteration, we assign the current key-value pair to the new object.
After the last iteration, all key-value pairs of the Map
are stored in the
object.
You can learn more about the related topics by checking out the following tutorials: