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 }
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
<!DOCTYPE html> <html lang="en"> <body> <pre id="output"></pre> <script> var map1 = new Map([ ['a', 10], ['b', 20], ['c', 30] ]); var displayOutput = ''; for (x of map1.entries()) { displayOutput += x[0] + ' - ' + x[1] + '\n'; } document.getElementById('output').innerHTML += displayOutput; </script> </body> </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.