To convert an array of objects into a map in JavaScript, you can utilize the Array.map() method to iterate 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 a Map object.

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:

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.