• JavaScript Video Tutorials

JavaScript - Map.entries() Method



The Map.entries() method in JavaScript is used to return a new map Iterator object that iterates over the [key-value] pairs of the map. Each element of the iterator is an array with two elements: the first element is the key, and the second element is the corresponding value from the map. The iterator follows the insertion order of the elements in the map.

The JavaScript Map.entries() method does not take any arguments; instead, it returns a new iterator object of the map.

Syntax

Following is the syntax of JavaScript Map.entries() method −

entries()

Parameters

This method does not accept any parameters.

Return value

This method returns an iterator object with the [key, value] pairs in a Map.

Examples

Example 1

In the following example, we are using the JavaScript Map.entries() method to return the [key, value] pairs of all the elements of the Map object in the order of their insertion.

<html>
<body>
   <script>
      const map = new Map();
      
      map.set('a', 'apple');
      map.set('b', 'banana');
      map.set('c', 'cherry');
      
      const iterator = map.entries();
      document.write(iterator.next().value, "<br>");
      document.write(iterator.next().value, "<br>");
      document.write(iterator.next().value);
   </script>
</body>
</html>

As we can see after executing the above program, it returned all the elements of the Map object in insertion order.

Example 2

When the Map object is empty, calling iterator.next().value returns "undefined" as a result, as there are no key-value pairs in the map to retrieve −

<html>
<body>
   <script>
      const map = new Map();
      
      const iterator = map.entries();
      document.write(iterator.next().value);
   </script>
</body>
</html>

So, trying to access the value property of the result of iterator.next(), when the map is empty will give "undefined" as a result.

Example 3

In this example, the for...of loop iterates through each entry in the map, and prints each [key, value] pair −

<html>
<body>
   <script>
      const map = new Map();

      map.set('a', 'apple');
      map.set('b', 'banana');
      map.set('c', 'cherry');
      
      for (let entry of map.entries()) {
         document.write(entry, "<br>");
      }
   </script>
</body>
</html>

If we execute above program, it prints all the key-value pairs present of the Map object.

Example 4

The Array.from() method converts the iterator of map entries into a regular array of [key, value] pairs.

<html>
<body>
   <script>
      const map = new Map();

      map.set('a', 'apple');
      map.set('b', 'banana');
      map.set('c', 'cherry');
      
      const entriesArray = Array.from(map.entries());
      document.write(entriesArray); // [['one', 1], ['two', 2], ['three', 3]]
   </script>
</body>
</html>

If we execute above program, it prints all the key-value pairs as a regular array.

Advertisements