# Convert a Map to an object in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 4, 2022, updated Jun 7, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-convert-map-to-object

> Learn how to use the Object.fromEntries() method to convert a Map to an object in JavaScript.

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()`:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/maps-javascript).
