Maps

Added in ES 2015.
For key-value pairs that need to be updated frequently the best collection to use is Map.
The map allows duplicate value, but each key must be unique.


Advantages over Objects

the key does not have to be a string
browsers are optimised for large maps, not large objects
maps preserve order


const myMap = new Map() 
myMap.set('prop1', 'value1')
myMap.set('prop2', 'value2')

console.log( myMap.get('prop1')

with chaining

const myMap = new Map() 
  .set('prop1', 'value1')
  .set('prop2', 'value2')

with an array

const myMap = new Map() 
  [
    ['prop1', 'value1'],
    ['prop2', 'value2']
]

removing

myMap.delete('prop1');  
myMap.clear(); // removing all

This does not return an array - this returns a MapIterator

myMap.keys()  // { prop1, prop2} 


Iterating a Map - for


const MyMap = new Map() 
   .set(10, 'text 1')
   .set(20, 'text 2')
   .set(30, 'text 3');

const MyArray = [ ...MyMap];
for (let I = 0; I < MyArray.length; i++) {
   const [id, name] = MyArray[i];
   // do something
}

Iterating a Map - for/of


const iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);  

for (const entry of iterable) {
  console.log(entry);
}

This returns an array of [key,value] for each iteration.

const myMap = new Map() 
myMap.set('prop1', 'value1')
myMap.set('prop2', 'value2')

for (const item of myMap) {
  console.log(item);
}


Adding default properties

const myDefaults = new Map() 
myDefaults.set('prop1','value1')
myDefaults.set('prop2','value2')

const myObject = new Map()
myObject.set('prop2','value2')

const myNewMap = new Map( [...myDefaults, ...myObject] );

map.set( sColChar, false ) => undefined ??




Methods


MethodMutatesDescription
entries  
clear  
delete  
get  
has  
keys  
set  
sort  


© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext