In JavaScript, you can create a new map object using the Map constructor:

const map = new Map()

map.set('John Doe', 'Admin')
map.set('Alex Hales', 'Manager')
map.set('Ali Feroz', 'User')

console.log(map)

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

The Map constructor can also accept an iterable object, such as an array, to initialize a map object with values:

const users = [
  ['John Doe', 'Admin'],
  ['Alex Hales', 'Manager'],
  ['Ali Feroz', 'User']
]

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

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

Additionally, you can convert a JavaScript object into a map object with values using the Object.entries() method:

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

const map = new Map(Object.entries(user))
console.log(map)

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

For further information on the Map object and how to create 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.