To convert an array of objects to a map, you can use the Array.map()
method to iterate through the array elements to create an array of key-value pairs. Then pass the 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'
// }
We passed a callback function to the Array.map()
method that gets called for each object in the array.
On each iteration, we return an array containing the key and the 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, we pass the result to the Map()
constructor to create a new instance of the Map
object.
An alternate approach is to use the Array.forEach()
method to convert the array of objects to a map. It is a three steps process:
- First, we use the
Map()
constructor to create an empty map object. - Call the
forEach()
method on the array to iterate through all objects. - On each iteration, use the
Map.set()
method to add the key value 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'
// }
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.