# Convert an object to a Map 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-object-to-map

> Learn how to convert an object to a Map object in JavaScript.

To convert an object to a `Map` in JavaScript, you can use the `Object.entries()` method to get an array of key-value pairs from the object, and then create a new `Map` object using the `Map` constructor and the obtained array.

Here's an example of how you can convert an object to a `Map` using `Object.entries()`:

```javascript
const user = {
  name: 'John Doe',
  age: 20,
  job: 'Engineer'
}

const kvPairs = Object.entries(user)

const map = new Map(kvPairs)
console.log(map)

// Map(3) { 'name' => 'John Doe', 'age' => 20, 'job' => 'Engineer' }
```

In this example, `Object.entries(user)` returns an array of key-value pairs from the `user` object, which is then used to create a new `Map` object using the `Map` constructor.

Alternatively, you can use the `Array.forEach()` method to [iterate over the object](https://attacomsian.com/blog/javascript-iterate-objects) keys and add each key-value pair to the `Map` using the `Map.set()` method:

```javascript
const user = {
  name: 'John Doe',
  age: 20,
  job: 'Engineer'
}

const map = new Map()

Object.keys(user).forEach(key => {
  map.set(key, user[key])
})

console.log(map)
// Map(3) { 'name' => 'John Doe', 'age' => 20, 'job' => 'Engineer' }
```

In this example, `Object.keys(user)` returns an array of keys from the `user` object. We then iterate over these keys using `forEach()` and use the `Map.set()` method to add each key-value pair to the `map` object.

If you want to convert the `Map` object back to an object, you can use the `Object.fromEntries()` method:

```javascript
const map = new Map([
  ['name', 'John Doe'],
  ['age', 20],
  ['job', 'Engineer']
])

const user = Object.fromEntries(map)

console.log(user)
// { name: 'John Doe', age: 20, job: 'Engineer' }
```

The `Object.fromEntries()` method takes an iterable of key-value pairs, such as an array, and returns a new object with the key-value pairs.

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).
