JavaScript – Iterate through Key-Value pairs of Map
To loop/iterate through key-value pairs of a Map in JavaScript, call entries() method on this map which returns an iterator for the key-value pairs in the Map, and use For-of Loop to iterate over the items.
Refer JavaScript For-of Loop.
Syntax
The syntax to use entries() method on a Map map1
to iterate over the key-value pairs using for-of loop is
for (const x of map1.entries()) { //x[0] is the key //x[1] is the value }
ADVERTISEMENT
Examples
In the following example, we take a Map with keys 'a'
, 'b'
, and 'c'
. We shall iterate through these key-value pairs using entries() method and for-of loop.
index.html
Conclusion
In this JavaScript Tutorial, we learned how to loop through key-value pairs of a Map in JavaScript using entries() method, with examples.