The Map
object in JavaScript allows us to create collections of key-value pairs. Keys in a Map
are unique and maintain their original insertion order. You can use any objects or primitives as keys and values.
Objects vs. Maps
Introduced in ES6 alongside the Set
object, the Map
object is similar to a JavaScript object used for storing key-value data. However, there are important distinctions:
Map
keys can be of any type, not limited to strings and symbols.- A
Map
object provides a property to retrieve the size of the collection. - By default, a
Map
does not contain any keys it only includes explicitly inserted entries.
Creating a new Map object
To create an empty map, use the Map()
constructor:
const items = new Map()
Alternatively, you can initialize a map with values by passing an iterable object like an array to the Map
constructor:
const items = new Map([
['🦅', 'Eagle'],
['🐶', 'Dog'],
['🐹', 'Hamster']
])
console.log(items)
// Map(3) { '🦅' => 'Eagle', '🐶' => 'Dog', '🐹' => 'Hamster' }
Another approach is to initialize a map with values from a JavaScript object:
const user = { name: 'John Doe', age: 30 }
const map = new Map(Object.entries(user))
console.log(map)
// Map(2) {
// 'name' => 'John Doe',
// 'age' => 30
// }
Adding elements to a Map
The set()
method is used to add elements to a Map
object:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
items.set('🚄', 'Train')
items.set(45, 'Number')
items.set(true, 'Boolean')
The set()
method is chainable, allowing you to combine multiple set()
calls:
const user = new Map()
user.set('name', 'Atta').set('age', 34)
console.log(user)
// Map(2) { 'name' => 'Atta', 'age' => 34 }
Since Map
keys are unique, calling set()
with the same key multiple times will update the value instead of creating multiple key-value pairs:
const animals = new Map()
animals.set('🐺', 'Wolf')
animals.set('🐺', 'Wolf Face')
console.log(animals) // Map(1) {"🐺" => "Wolf Face"}
Adding objects to a Map
Since the Map
object allows storing any data type as keys or values, you can include complex objects like object literals, arrays, and even functions:
const props = {
browser: 'Chrome',
os: 'Ubuntu 19.04'
}
const hamburger = () => '🍔'
const things = new Map()
things.set('birds', ['🦉', '🦅'])
things.set('user', { name: 'John Doe', planet: 'Earth' })
things.set(props, 59)
things.set(hamburger, 'What is the food?')
things.get(props) // 59
things.get(hamburger) // What is the food?
Getting an element from a Map
To retrieve elements from a Map
object, use the get()
method:
const user = { name: 'Atta', age: 30 }
const items = new Map()
items.set('user', user)
items.set('rank', 12)
console.log(items.get('rank')) // 12
console.log(items.get('user')) // { name: 'Atta', age: 30 }
Checking if an element exists in a Map
To determine if an element exists in a Map
object, use the has()
method:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
console.log(items.has('🐶')) // true
console.log(items.has('🐺')) // false
Getting the number of elements in a Map
The Map
object provides the size
property to retrieve the number of elements in the collection:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
console.log(items.size) // 2
Deleting an element from a Map
To remove an element from a Map
object, use the delete()
method:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
console.log(items.delete('🐶')) // true
console.log(items.delete('🐶')) // false (already removed)
console.log(items.delete('🚄')) // false (not found)
Deleting all elements in a Map
To delete all entries in a Map
object, use the clear()
method:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
items.clear()
console.log(items.size) // 0
Iterating over Map keys
The keys()
method returns an iterator object containing all the keys in a Map
object. You can use it with a for...of
loop to iterate over the keys:
let john = { name: 'John Doe' },
alex = { name: 'Alex' },
pretti = { name: 'Pretti' }
const team = new Map([
[john, 'Manager'],
[alex, 'Lead'],
[pretti, 'Developer']
])
for (const user of team.keys()) {
console.log(user)
}
// { name: 'John Doe' }
// { name: 'Alex' }
// { name: 'Pretti' }
Iterating over Map values
To iterate over the values in a Map
object, use the values()
method:
let john = { name: 'John Doe' },
alex = { name: 'Alex' },
pretti = { name: 'Pretti' }
const team = new Map([
[john, 'Manager'],
[alex, 'Lead'],
[pretti, 'Developer']
])
for (const role of team.values()) {
console.log(role)
}
// Manager
// Lead
// Developer
Iterating over Map elements
You can use a for...of
loop to iterate over all key-value pairs in a Map
object. The order of iteration follows the original insertion order of the keys:
const foods = new Map([
['🍌', 'Banana
'],
['🍕', 'Pizza'],
['🥒', 'Cucumber'],
['🌽', 'Maize']
])
for (const [key, value] of foods) {
console.log(`${key}: ${value}`)
}
// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber
// 🌽: Maize
Alternatively, you can use the forEach()
method to iterate over all elements:
foods.forEach((value, key) => {
console.log(`${key}: ${value}`)
})
// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber
// 🌽: Maize
The Map
object also provides the entries()
method, which returns an iterable for key-value pairs [key, value]
:
for (const [key, value] of foods.entries()) {
console.log(`${key}: ${value}`)
}
You can call the next()
method on the iterable returned by entries()
to traverse the key-value pairs one by one:
const entries = foods.entries()
console.log(entries.next()) // { value: ["🍌", "Banana"], done: false }
Converting a Map to an array
To convert a Map
object to a two-dimensional array, you can use the Array.from()
method:
const foods = new Map([
['🍌', 'Banana'],
['🍕', 'Pizza'],
['🥒', 'Cucumber'],
['🌽', 'Maize']
])
const arr = Array.from(foods)
console.log(arr)
// [
// ['🍌', 'Banana'],
// ['🍕', 'Pizza'],
// ['🥒', 'Cucumber'],
// ['🌽', 'Maize']
// ]
Alternatively, you can use the spread operator (...
) to convert a Map
object to an array:
const arr = [...foods]
console.log(arr)
// [
// ['🍌', 'Banana'],
// ['🍕', 'Pizza'],
// ['🥒', 'Cucumber'],
// ['🌽', 'Maize']
// ]
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.