You can use the Map
object constructor to create a new map object in JavaScript:
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 also accepts 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'
// }
Finally, you can also 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' }
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.