In JavaScript, we have two main data structures: Map and Object. Map is a collection of key-value pairs, whereas Object is a collection of properties. Sometimes, we may need to convert a Map into an Object to perform certain operations. Here’s a guide on how to do that.
Using Object.fromEntries()
One way to convert a Map to an Object is to use the Object.fromEntries() method. This method takes an iterable (such as an Array or a Map) containing key-value pairs and returns an Object with those key-value pairs.
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
const myObj = Object.fromEntries(myMap);
console.log(myObj); // { a: 1, b: 2, c: 3 }
Using Object.assign()
Another way to convert a Map to an Object is to use the Object.assign() method. This method takes one or more source objects and copies their properties to a target object. We can create an empty object as the target and pass the Map as the source.
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
const myObj = Object.assign({}, myMap);
console.log(myObj); // { a: 1, b: 2, c: 3 }
Iterating over the Map
We can also convert a Map to an Object by iterating over the Map and manually adding the key-value pairs to an Object.
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
const myObj = {};
for (let [key, value] of myMap) {
myObj[key] = value;
}
console.log(myObj); // { a: 1, b: 2, c: 3 }
That’s it! These are the three ways to convert a Map to an Object in JavaScript. Choose the method that best suits your needs and use it in your code.