This post will describe the methods for converting JavaScript maps into objects.
How Does a JS Map Return an Object?
JavaScript Map returns an object using the following methods:
- Array.from() method with reduce() method
- map.entries() method with reduce() method
Method 1: JS Map Return an Object Using Array.from() Method With reduce() Method
To return an object from a Map, first, convert it into an array using the “Array.from()” method and then call the “reduce()” method. The reduce() method calls the callback function called “reducer” on every array element of Map and returns the key-value pairs to the reduce() method. The Array.from() is a static method of an Array object. It creates a new array instance from iterable objects such as Map and Set.
Example
First, create a new Map object:
Add elements in Map in a key-value pair using the set() method:
map.set(2, "HTML");
map.set(3, "CSS");
Call the Array.from() method with reduce() method to convert the map to an object:
obj[key] = value;
return obj;
}, {});
Finally, print the object on the console:
The output indicates that the map is successfully converted to an object:
Method 2: JS Map Return an Object Using the map.entries() Method With reduce() Method
Another way to return an object from a JavaScript Map is to use the “map.entries()” method with the “reduce()” method. The entries() method outputs a new iterator object that comprises the [key, value] pairs in an array, and the reduce() method calls the reducer callback function on each element of Map. It returns the key-value pairs to the reduce() method.
Example
Here, we will call the map.entries() method with reduce() method for converting a map to an object:
obj[key] = value;
return obj;
}, {});
Output
That’s all about JS Map return Objects using JavaScript.
Conclusion
JavaScript Map returns an object using the “Array.from()” method with the “reduce()” method or the “map.entries()” method with the “reduce()” method. Both of these approaches efficiently return an object from a Map while the map.entries() method with reduce() method is fast. This post described the methods for converting JavaScript maps into objects.