How to iterate through map in JavaScript?

Are you tired of figuring out of how to iterate through map in JavaScript?

This article will teach you how to go through these pairs effectively and we will extensively explore the concept of iterating through map objects in JavaScript.

So, let’s begin this journey of mastering the art on how to iterate through a map in JavaScript!

What is map in JavaScript?

Map is a collection of key-value pairs that accommodates any data type for both keys and values in JavaScript.

It is somehow similar with an object, but there are notable distinctions.

Notably, a Map allows keys of diverse data types, such as objects and functions, while objects are restricted to using strings or symbols as keys.

Moreover, Mapping in JavaScript allows us to store and manipulate key-value pairs, making efficient iteration through these maps essential for achieving optimal performance and functionality.

Here’s an example of how to create and use a Map in JavaScript:


const myMap = new Map();

// Set key-value pairs
myMap.set('name', 'Itsourcecode');
myMap.set('age', 18);
myMap.set('gender', 'male');

// Get the value associated with a key
console.log(myMap.get('name')); // Output: Itsourcecode

// Check if a key exists in the Map
console.log(myMap.has('age')); // Output: true

// Delete a key-value pair
myMap.delete('gender');

// Clear all key-value pairs
myMap.clear();

Different ways on how to iterate through a map in JavaScript?

There are several ways to iterate through a Map in JavaScript. Here are some of the most common methods:

Solution 1: Use the forEach method

The forEach method is a built-in method of the Map object that allows you to iterate through the key-value pairs in the Map.

It takes a callback function as an argument, which is called once for each key-value pair in the Map.

The callback function receives three arguments: the value of the current element, the key of the current element, and the Map object being traversed.

Here’s an example:

const map = new Map();
map.set("x", 10);
map.set("y", 20);
map.set("z", 30);

map.forEach((value, key) => {
    console.log(`key: ${key}, value: ${value}`);
});

Output:

key: x, value: 10
key: y, value: 20
key: z, value: 30

Here’s another example:

const map = new Map([
  ["Address", "New York"],
  ["Gender", "Male"],
  ["Age", 18],
]);

map.set("Name", "Itsourcecode");

map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Output:

Address: New York
Gender: Male
Age: 18
Name: Itsourcecode

Solution 2: Use the for…of loop

The for…of loop is another way to iterate through a Map in JavaScript. You can use it in combination with the keys(), values(), or entries() methods of the Map object to iterate over the keys, values, or entries of the Map, respectively.

Here’s an example:

const map = new Map();
map.set("x", 10);
map.set("y", 20);
map.set("z", 30);

for (const key of map.keys()) {
    console.log(`key: ${key}`);
}

for (const value of map.values()) {
    console.log(`value: ${value}`);
}

for (const [key, value] of map.entries()) {
    console.log(`key: ${key}, value: ${value}`);
}

Output:

key: x
key: y
key: z
value: 10
value: 20
value: 30
key: x, value: 10
key: y, value: 20
key: z, value: 30

Here’s another example:

const map = new Map([
  ["Address", "New York"],
  ["Gender", "Male"],
  ["Age", 18],
]);

map.set("Name", "Sourcecode");


for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}

Output:

Address: New York
Gender: Male
Age: 18
Name: Sourcecode

Solution 3: Use the default iterator

The default iterator for a Map is the same as using map.entries(), so you can use a for…of loop to iterate over the entries of a Map without explicitly calling map.entries().

Here’s an example:

const map = new Map();
map.set("x", 11);
map.set("y", 22);
map.set("z", 33);

for (const [key, value] of map) {
    console.log(`key: ${key}, value: ${value}`);
}

Output:

key: x, value: 11
key: y, value: 22
key: z, value: 33

How to iterate over Object’s property-value pairs?

In JavaScript, numerous techniques exist for iterating over an object’s property-value pairs. Below are some of the most frequently used approaches:

Use a for…in loop

The for…in loop iterates over the enumerable properties of an object, including inherited properties.

To iterate only over the object’s own properties, you can use the hasOwnProperty method to check if the property belongs to the object.

Here’s an example:

const obj = {Name: 'Itsourcecode', Age: 18, Gender: 'male'};
for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        console.log(`${prop}: ${obj[prop]}`);
    }
}

Output:

Name: Itsourcecode
Age: 18
Gender: male

Use the Object.keys

The Object.keys method returns an array of an object’s own enumerable properties. You can then use a for loop or a forEach method to iterate over the array of keys.

Here’s an example:

const obj = {Name: 'Caren', Age: 18, Gender: 'female'};
const keys = Object.keys(obj);
keys.forEach(key => {
    console.log(`${key}: ${obj[key]}`);
});

Output:

Name: Caren
Age: 18
Gender: female

Use the Object.entries

The Object.entries method returns an array of an object’s own enumerable property [key, value] pairs. You can then use a for loop or a forEach method to iterate over the array of entries.

Here’s an example:

const obj = {Name: 'Glad', Age: 18, Gender: 'female'};
const entries = Object.entries(obj);
entries.forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

Output:

Name: Glad
Age: 18
Gender: female

Conclusion

In conclusion, this article provides a comprehensive guide on how to iterate through maps and objects in JavaScript.

It covers three main methods for iterating through a Map along with examples: using the forEach method, the for…of loop with keys(), values(), or entries() methods, and using the default iterator.

We are hoping that this article provides you with enough information that help you understand on how to iterate through map in JavaScript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment