The map object holds the data in the form of key-value pair.
The value may be any object or primitive data type. The map object iterates the items in insertion order.
2. Agenda
Introduction
Object vs Map
Map Syntax
Method on Map
Live Examples
WeakMap
WeakMap syntax
Methods on WeakMap
Live Example
3. Introduction
The map object holds the data as key-value pair.
The value may be any object or primitive data values.
A map object iterates its elements in insertion order.
Using for…of loop we can get key, values as an array for each iteration.
We can give NaN as key in map.
4. Object vs Map
Object allows keys only either strings or symbols. But map can allow any
type of data like primitives, functions, objects, etc.
We can get values from object by using object[“key”] or object.key. But to
get values from map by using map.get(“key”) method.
Data in the object can be any order. But in map the order of the keys based
on insertion of the data to map.
7. Insert Data into Map
let employeeMap = new Map( );
employeeMap.set(“empId”, 46);
employeeMap.set(“name”, “Jagadeesh”);
employeeMap.set(“designation”, “SSE”);
8. Get Data from Map
Using forEach
Using for…of
Manual approach
9. Get Data from Map(cont…)
forEach
var map = new Map( );
map.forEach( function( key, val ){
console.log( key + “ “ + val );
});
10. Get Data from Map(cont…)
For…of
var map = new Map( );
for( let [ key, val ] of map ) {
console.log( key + “ “ + val );
}
11. Get Data from Map(cont…)
For…of ( cont…)
var map = new Map( );
for( let key of map.keys( ) ) {
console.log( key );
}
12. Get Data from Map(cont…)
For…of ( cont…)
var map = new Map( );
for( let val of map.values( ) ) {
console.log( val );
}
13. Get Data from Map(cont…)
For…of ( Cont…)
var map = new Map( );
for( let [ key, val ] of map.entries( ) ) {
console.log( key + “ “ + val );
}
14. Get Data from Map(cont…)
Manual
var map = new Map( );
console.log( map.get( key ) ); OR
var keys = map.keys( );
for ( let index = 0; index < keys.length; index++ ){
console.log( map.get( keys[ index ] ) );
}
15. WeakMap
The weakmap object holds the data as key-value pair.
In weakmap the keys are weakly referenced.
The keys must be objects, and the values can be any values.
We cannot get length of weakmap.
Weakmap not allowed to get keys by keys() method.