. Advertisement .
..3..
. Advertisement .
..4..
Can’t find a way to convert map to object in JavaScript? Don’t panic just yet; we are here to help. Check out this guide to find out the method to perform this task. You will find the procedure is much simpler than you think. Let’s get started!
Convert Map To Object In JavaScript Using Object.fromEntries()
You can call the function Object.fromEntries() with a Map as a value input to convert Map to object in the JavaScript programming language.
const map = new Map([
['user1', 'John'],
['user2', 'Kate'],
['user3', 'Peter'],
]);
const obj = Object.fromEntries(map);
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);
The method Object.fromEntries accepts an iterable, like the Map, and produces an object that contains all of the iterable’s key-value pairs. For instance, when we supply a key-value pair array to the constructor Map(), it can instantly alter that array:
const arr = [
['user1', 'John'],
['user2', 'Kate'],
['user3', 'Peter'],
];
const obj = Object.fromEntries(arr);
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);
As you can see, here, we utilized the method Object.fromEntries for the Map to object conversion.
Keep in mind this method only accepts an iterable with key-value pairs, such as a Map or an array.
Convert Map To Object In JavaScript By Iterate Over Map
Iterating over the items of your Map and creating a brand-new key for each object is another method for converting the map to the object. We will set the value and name of the key for each entry to correspond to each entry value and name.
Here is an example for you to use as a reference.
const map = new Map([
['user1', 'John'],
['user2', 'Kate'],
['user3', 'Peter'],
]);
const obj = {};
map.forEach((value, key) => {
obj[key] = value;
});
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);
Notice that you may iterate over Map using the loop for…of.
Below is a sample.
const map = new Map([
['user1', 'John'],
['user2', 'Kate'],
['user3', 'Peter'],
]);
const obj = {};
for (const [key, value] of map) {
obj[key] = value;
}
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);
Iterables with key-value pairs as their elements are required by the constructor Map(). Therefore, a two-dimensional array similar to the one returned by the method Object.entries is ideal.
The Bottom Line
So there you have our complete guide on how to convert map to object in JavaScript. As you can see, the procedure is quite simple and easy to learn. Just put our method into practice, and you will soon accomplish your task.For those who want to learn more map-related skills in the JavaScript programming language, we have prepared a detailed guide on converting an array of objects to a map. Give it a check; we can guarantee this skill will come in handy for JavaScript programmers at some point.
Leave a comment