How to iterate an ES6 Map, and other Javascript objects
TLDR;
- With an ES6 Map, use
for (const [key, value] of myMap)
, this is equivalent tofor (const [key, value] of myMap.entries())
. - With an ES6 Set, use
for (const value of mySet)
, this is equivalent tofor (const value of mySet.values())
. - With an array, use
for (const value of myArray)
, this is equivalent tofor (const value of myArray.values())
. - With an ordinary object, use
for (const [key, value] of Object.entries(obj))
.
Other notes:
- Besides above methods, there are also
- Map.prototype.keys(), Map.prototype.entries(), Map.prototype.values().
- Set.prototype.values(), Set.prototype.entries(): set's entries have the value of[value, value]
.
- Array.prototype.keys(), Array.prototype.values(), Array.prototype.entries().
- Object.keys(), Object.values(), Object.entries(). Object`'s
/.keys()
.values()
/.entries()
return arrays whileMap/Set/Array
's ones return iterable objects.- To generate an array from a list of integers. Use
[...new Array(5).keys()].map(index => generateValue(index))
. - Convert an ordinary object to ES5 Map:
Object.entries(obj).reduce((map, [key, value]) => map.set(key, value), new Map())
.
From ES5 Map to an ordinary object:Object.fromEntries(myMap.entries())
. - To create an array from a list of elements, use literal notation, or Array.of(), instead of new Array().
new Array(3)
returns an array of 3 empty elements, whileArray.of(3)
returns[3]
.