JavaScript Map entries()
Syntax & Examples

Map.entries() method

The entries() method of the Map object in JavaScript returns a new Iterator object that contains a two-member array of [key, value] for each element in the Map object in insertion order.


Syntax of Map.entries()

The syntax of Map.entries() method is:

entries()

This entries() method of Map returns a new Iterator object that contains a two-member array of [key, value] for each element in the Map object in insertion order.

Return Type

Map.entries() returns value of type Iterator.



✐ Examples

1 Using entries() to iterate over a Map

In JavaScript, we can use the entries() method to get an iterator object and use it to iterate over the key-value pairs of a Map.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the entries() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each key-value pair to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.entries();
for (const entry of iterator) {
  console.log(entry);
}

Output

[ 'a', 1 ]
[ 'b', 2 ]
[ 'c', 3 ]

2 Using entries() to convert a Map to an array of key-value pairs

In JavaScript, we can use the entries() method to convert a Map object to an array of key-value pairs.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the entries() method to get an iterator object iterator for the map.
  3. Convert the iterator to an array using the Array.from() method and store it in the variable arrayOfEntries.
  4. Log arrayOfEntries to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.entries();
const arrayOfEntries = Array.from(iterator);
console.log(arrayOfEntries);

Output

[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]

3 Using entries() with a Map of objects

In JavaScript, we can use the entries() method to iterate over a Map object containing objects as values.

For example,

  1. Create a new Map object map with initial key-value pairs where values are objects.
  2. Use the entries() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each key-value pair to the console using console.log().

JavaScript Program

const map = new Map([
  ['person1', { name: 'John' }],
  ['person2', { name: 'Jane' }]
]);
const iterator = map.entries();
for (const entry of iterator) {
  console.log(entry);
}

Output

[ 'person1', { name: 'John' } ]
[ 'person2', { name: 'Jane' } ]

Summary

In this JavaScript tutorial, we learned about entries() method of Map: the syntax and few working examples with output and detailed explanation for each example.