You can convert a Map object to an object in JavaScript using the Object.fromEntries() method. The Object.fromEntries() method takes an iterable of key-value pairs and returns a new object.
Here's an example of how you can convert a Map to an object using Object.fromEntries():
const map = new Map([
['name', 'John Doe'],
['age', 20],
['job', 'Doctor']
])
const user = Object.fromEntries(map)
console.log(user)
// { name: 'John Doe', age: 20, job: 'Doctor' }
In this example, the Object.fromEntries() method is called with the map object as the argument, which contains key-value pairs. The method converts the map object to an object literal with the same key-value pairs.
The Object.fromEntries() takes an iterable, such as a Map, and returns an object containing the key-value pairs of the iterable:
const kvPairs = [
['name', 'John Doe'],
['age', 20],
['job', 'Doctor']
]
const user = Object.fromEntries(kvPairs)
console.log(user)
// { name: 'John Doe', age: 20, job: 'Doctor' }
In this case, the kvPairs array directly represents the key-value pairs, and Object.fromEntries() converts them into an object.
An alternate approach is to use the Map.forEach() method to iterate over the entries of the Map object and create a new key on the object for each of them:
const map = new Map([
['name', 'John Doe'],
['age', 20],
['job', 'Doctor']
])
const user = {}
map.forEach((value, key) => {
user[key] = value
})
console.log(user)
// { name: 'John Doe', age: 20, job: 'Doctor' }
If you want to convert the object back to a Map object, you can use the Object.entries() method to get an array of key-value pairs from the object, and then create a new Map using the Map constructor:
const user = {
name: 'John Doe',
age: 20,
job: 'Doctor'
}
const map = new Map(Object.entries(user))
console.log(map)
// Map(3) { 'name' => 'John Doe', 'age' => 20, 'job' => 'Doctor' }
In this example, Object.entries(user) returns an array of key-value pairs, which is then used to create a new Map object.
To learn more about the Map object and how to create collections of key-value pairs in JavaScript, you can refer to this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.