The Map
object allows us to create collections of key-value pairs in JavaScript. Keys in the Map
are unique and appear in the original insertion order. You can store any objects and primitives as keys and values.
Objects vs. Maps
The Map
object was introduced in ES6 along with the Set
object. It is similar to a JavaScript object used for storing key-value data. However, there are some important differences:
- The
Map
keys can be of any type and are not limited to strings and symbols. - A
Map
object provides a property to get the size of the collection. - A
Map
does not contain any keys by default. It only contains what is explicitly put into it.
Create a new Map object
You can use the Map()
constructor to create an empty map:
const items = new Map()
You can also pass an iterable object, such as an array, to the Map
constructor to initialize a map with values:
const items = new Map([
['🦅', 'Eagle'],
['🐶', 'Dog'],
['🐹', 'Hamster']
])
console.log(items)
// Map(3) { '🦅' => 'Eagle', '🐶' => 'Dog', '🐹' => 'Hamster' }
Alternatively, you can also 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
// }
Add elements to a Map
You can use the set()
method 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, which means you can combine multiple set()
calls together, as shown below:
const user = new Map()
user.set('name', 'Atta').set('age', 34)
console.log(user)
// Map(2) { 'name' => 'Atta', 'age' => 34 }
Since the Map
keys are unique, calling set()
more than once with the same key won't add multiple key-value pairs. Instead, the value part is replaced with the newest value, as shown below:
const animals = new Map()
animals.set('🐺', 'Wolf')
animals.set('🐺', 'Wolf Face')
console.log(animals) // Map(1) {"🐺" => "Wolf Face"}
Add objects to a Map
Since the Map
object allows us to store any data type as a key or value, we can store complex objects like object literals, arrays, and even functions as keys and values:
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?
Get an element from a Map
You can use the get()
method to get elements from a Map
object:
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 }
Check if an element exists in a Map
To check if an element exists in the Map
object, you can use the has()
method:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
console.log(items.has('🐶')) // true
console.log(items.has('🐺')) // false
Get the number of elements in a Map
The Map
object provides the size
property to get the number of elements in the collection:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
console.log(items.size) // 2
Delete an element from a Map
To remove an element from the Map
object, you can 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
Delete all elements in a Map
To delete all entries in the Map
object, you can use the clear()
method:
const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
items.clear()
console.log(items.size) // 0
Iterate over Map keys
You can use the keys()
method to get all keys in the Map
object. It returns a new iterator object containing the keys of all elements in the map.
The following example demonstrates how you can use the keys()
method and for...of
loop to iterate over the Map
object 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' }
Iterate over Map values
The Map
object provides the values()
method to get an iterator object containing values for all the elements in the map:
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
Iterate over Map elements
You can use the for...of
loop to iterate over all key-value pairs in the Map
object. Since the Map
remembers the original insertion order of the keys, the key-value pairs are returned in the same order as they were inserted:
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 also 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 has the entries()
method that returns an iterable for entries [key, value]
:
for (const [key, value] of foods.entries()) {
console.log(`${key}: ${value}`)
}
You can call the next()
method on the iterable returned by the entries()
method to traverse the key-value pairs one by one:
const entries = foods.entries()
console.log(entries.next()) // {value: ["🍌", "Banana"], done: false}
Convert a Map to an array
You can convert a Map
object to a two-dimensional array using 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.