Finally, we can use Map in javascript. What is Map?
The
Map
object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
In this article, I will sum up the methods, properties and some common mistake about Map. You can run all the below codes in browser console.
How to create a Map:
let map = new Map() //remember put new before Map()!!!
console.log(map) //Map{}
create a Map with initial value by array:
let map = new Map([['key1', 'value1'], ['key2', 'value2']])
console.log(map) //Map { key1 → "value1", key2 → "value2" }
We can use object, function, null, undefined, NaN, array, number, string, symbol, bool… every thing as a key.
For object
, function
, array
, if we declare them inside Map function, Map will treat each one as unique key since the comparison is done by reference. For example, each time you run {}, it creates a new empty object, so when you check them by {} === {}
, you’re comparing two different objects. This comparison is done by reference, so it returns false. Hence, we should declared with a named identifier to refer object
, function
, array
if we want to use them as key.
For null
, undefined
, NaN
, bool
, if the result is equal to them, you can get the correct value, for example map.get(1===1)
it will return the value of key true
.
For symbol
, every symbol value returned from Symbol()
is unique, Symbol('abc') === Symbol('abc') // false
therefor Map will treat each one as unique key.
To count how many entries are in a Map
, we can call map.size
. One of the common mistake is people will call map.length
which is not correct.
let map = new Map([['key1', 'value1'], ['key2', 'value2']])
console.log(map.size) //2
Here are some methods that commonly used:
map.set(key)
map.set(key,value)
Sets the value
for the key
in the Map
object and returns the Map
object.
let map = new Map([[1,1]])
console.log(map) //Map { 1 => 1 } console.log(map.set(2)) //Map { 1 => 1, 2 => undefined } console.log(map.set(2,2)) //Map { 1 => 1, 2 => 2 }
map.get(key)
Returns the value associated to the key
, or undefined
if there is none.
let map = new Map([[1,1],[2,2]])
console.log(map) //Map { 1 => 1, 2 => 2 } console.log(map.get(1)) //1
console.log(map.get(3)) //undefined
map.has(key)
Returns a boolean asserting whether a value has been associated to the key
in the Map
object or not.
let map = new Map([[1,1],[2,2]])
console.log(map) //Map { 1 => 1, 2 => 2 } console.log(map.has(1)) //true
console.log(map.has(3)) //false
map.clear()
Remove all key-value pairs from the Map
object and dose not return anything.
let map = new Map([[1,1],[2,2]])
console.log(map) //Map { 1 => 1, 2 => 2 }
console.log(map.clear()) //undefined
console.log(map) //Map {}
map.delete(key)
Returns true
if an element in the Map
object existed and has been removed, or false
if the element does not exist.
let map = new Map([[1,1],[2,2]])
console.log(map) //Map { 1 => 1, 2 => 2 } console.log(map.delete(null)) //false
console.log(map.delete(1)) //true
console.log(map) //Map { 2 => 2 }
For a sequential access of items in the collection, Map provides below methods:
map.forEach((value,key)=>{...})
Calls once for each key-value pair present in the Map
object in insertion order.
let map = new Map([[1,"value 1"],[2,"value 2"]])
console.log(map) //Map { 1 => 1, 2 => 2 } map.forEach((value,key)=>console.log(key,":",value))
//1 : value 1 , 2 : value 2
If we want to modify the map
object in forEach
, we can add the third parameter.
map.forEach((value,key,map)=>{...})
let map = new Map([[1,"value 1"],[2,"value 2"]])
console.log(map) //Map { 1 => 1, 2 => 2 } map.forEach((value,key,map)=>map.set(key,"new value")) console.log(map) //Map { 1 => 'new value', 2 => 'new value' }
You may want to use Iterator
rather than forEach
if it involves async/await, to learn more, please read my story about async/await with forEach
Furthermore, Map provides three methods return Iterator
objects, one for keys, one for values, one for keys and values.
map.keys()
Returns a new Iterator
object that contains the keys for each element in the Map
object in insertion order.
map.values()
Returns a new Iterator
object that contains the values for each element in the Map
object in insertion order.
map.entries()
Returns a new Iterator
object that contains an array of [key, value]
for each element in the Map
object in insertion order.
let map = new Map([[1,"value 1"],[2,"value 2"]])
console.log(map) //Map { 1 => "value 1", 2 => "value 2" }
for (let value of map.keys() ) {
console.log(value) //1 ; 2
}for (let value of map.values() ) {
console.log(value) //value 1 ; value 2
} for (let value of map.entries() ) {
console.log(value[0],":",value[1]) //1:value 1 ; 2:value 2
}
I hope this will help you understand more about Map. All the example code can be run in browser console, you can have a try! Thanks for reading!