TypeScript tutorial: Lesson 24 – Map


Starting with ECMAScript 2015, 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.

Create a Map:

var myMap = new Map()

Or initial by an Array

var myMap2 = new Map([[2,2],[1,1]])

Or initial by other Map

var myMap3 = new Map(myMap)

Setting object properties

Use set(key, value) method:

myMap.set(2,2)
myMap.set(1,1)
myMap.set(3,3)

for(var j of myMap){
    console.log(j)
}

Result:

[ 2, 2 ]
[ 1, 1 ]
[ 3, 3 ]

Getting object properties

Use get(key) method:

console.log(myMap2.get(1)) //1

Delete an object property

Use delete(key) method:

console.log(myMap2.delete(1)) //true

Size of Map

console.log(myMap.size) //3

Iterating Map with forEach()

myMap.forEach(function(value, key) {
    console.log(key + ' = ' + value)
})

Result:

2 = 2
1 = 1
3 = 3

Instance methods
Map.prototype.clear()
Removes all key-value pairs from the Map object.
Map.prototype.delete(key)
Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.
Map.prototype.get(key)
Returns the value associated to the key, or undefined if there is none.
Map.prototype.has(key)
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
Map.prototype.set(key, value)
Sets the value for the key in the Map object. Returns the Map object.

Converting an Object to a Map
In ES8, you can use Object.entries() to convert the object into an array

const obj = { hello: 'world', say: 'hi' }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map(2) {"hello" => "world", "say" => "hi"}

Converting a Map to an Array

const arr = [...map]
console.log(arr); //Array [Array ["hello", "world"], Array ["say", "hi"]]

Converting a Map to an Object
In ES10, you can use Object.fromEntries() to convert array to object.

const obj2 = Object.fromEntries([...map])
console.log(obj2); //Object { hello: "world", say: "hi" }

Leave a Reply