# Convert an array of objects 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-array-of-objects-to-map

> Learn how to convert an array of nested objects to a Map object in JavaScript.

To convert an array of objects into a map in JavaScript, you can utilize the `Array.map()` method to [iterate](https://attacomsian.com/blog/javascript-loops) through the array elements and create an array of key-value pairs. Subsequently, you can pass this array of key-value pairs to the `Map()` constructor to [create](https://attacomsian.com/blog/javascript-create-map-object) a `Map` object.

```javascript
const users = [
  { name: 'John Doe', role: 'Admin' },
  { name: 'Alex Hales', role: 'Manager' },
  { name: 'Ali Feroz', role: 'User' }
]

const kvPairs = users.map(u => [u.name, u.role])

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

// Map(3) {
//     'John Doe' => 'Admin',
//     'Alex Hales' => 'Manager',
//     'Ali Feroz' => 'User'
// }
```

In the above code, a callback function is provided to the `Array.map()` method, which is executed for each object in the array. During each iteration, an array is returned containing the key and value for each object, resulting in an array of key-value pairs:

```javascript
const users = [
  { name: 'John Doe', role: 'Admin' },
  { name: 'Alex Hales', role: 'Manager' },
  { name: 'Ali Feroz', role: 'User' }
]

const kvPairs = users.map(u => [u.name, u.role])
console.log(kvPairs)

// [
//     [ 'John Doe', 'Admin' ],
//     [ 'Alex Hales', 'Manager' ],
//     [ 'Ali Feroz', 'User' ]
// ]
```

Finally, the resulting array is passed to the `Map()` constructor to create a new instance of the `Map` object.

Alternatively, you can use the `Array.forEach()` method to convert the array of objects to a map. This approach involves three steps:

1. Create an empty map object using the `Map()` constructor.
2. Use the `forEach()` method on the array to iterate through all the objects.
3. During each iteration, utilize the `Map.set()` method to add the key-value pair to the map.

```javascript
const users = [
  { name: 'John Doe', role: 'Admin' },
  { name: 'Alex Hales', role: 'Manager' },
  { name: 'Ali Feroz', role: 'User' }
]

const map = new Map()

users.forEach(u => {
  map.set(u.name, u.role)
})

console.log(map)
// Map(3) {
//     'John Doe' => 'Admin',
//     'Alex Hales' => 'Manager',
//     'Ali Feroz' => 'User'
// }
```

For further information on the `Map` object and its usage for creating collections of key-value pairs in JavaScript, you can refer to [this article](https://attacomsian.com/blog/maps-javascript).
