To convert a Map
to an object, you can use the Object.fromEntries()
method by passing it the Map
object as an argument:
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' }
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' }
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 the Map
object, use the Object.entries()
method:
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' }
Read this article to learn more about the Map
object and how to use it to create collections of key-value pairs in JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.