Skip to content

JavaScript Map keys() | Method

  • by

JavaScript Map keys() method is used to extract the keys from a given map object and return the iterator object of keys.

obj.keys()  

This method returns an object of a new Map iterator. This object contains the key for each element. It maintains insertion order.

JavaScript Map keys

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    var map = new Map();  
    map.set(1,"ABC");  
    map.set(2,"XYZ");  
    map.set(3,"PQR");  

    var itr = map.keys();  

    console.log(itr.next().value);  
    console.log(itr.next().value);  
    console.log(itr.next().value);  
    console.log(itr.next().value); 
    
  </script>
</body>
</html>

Output:

JavaScript Map keys Method

More example Using keys()

const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

const mapIter = myMap.keys();

console.log(mapIter.next().value); // "0"
console.log(mapIter.next().value); // 1
console.log(mapIter.next().value); // Object

Using for loop

<script >
    var map = new Map();  
    map.set(1,"ABC");  
    map.set(2,"XYZ");  
    map.set(3,"PQR");  

    var itr = map.keys();  

    for(i=0;i<map.size;i++)  
    {  
      console.log(itr.next().value);  
    }  
</script>

Do comment if you have any doubts or suggestions on this Js map method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *