Map Iteration
Map Iteration
Section titled “Map Iteration”Introduction
Section titled “Introduction”Maps are directly iterable, which makes them more convenient to iterate than objects.
for…of
Section titled “for…of”const map = new Map([ ['a', 1], ['b', 2], ['c', 3]]);
// Iterate entries (default)for (const [key, value] of map) { console.log(key, value);}// a 1// b 2// c 3keys(), values(), entries()
Section titled “keys(), values(), entries()”const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
// Keysfor (const key of map.keys()) { console.log(key); // 'a', 'b', 'c'}
// Valuesfor (const value of map.values()) { console.log(value); // 1, 2, 3}
// Entriesfor (const entry of map.entries()) { console.log(entry); // ['a', 1], ['b', 2], ['c', 3]}forEach
Section titled “forEach”map.forEach((value, key, map) => { console.log(`${key}: ${value}`);});// a: 1// b: 2// c: 3Converting to Array
Section titled “Converting to Array”const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const keys = [...map.keys()]; // ['a', 'b', 'c']const values = [...map.values()]; // [1, 2, 3]const entries = [...map.entries()]; // [['a',1], ['b',2], ['c',3]]const asArray = [...map]; // [['a',1], ['b',2], ['c',3]]Summary
Section titled “Summary”- Maps are directly iterable with
for...of keys(),values(),entries()return iteratorsforEach(callback)provides value, key, and map- Spread operator converts Map to array of entries