Loop through a Dictionary in Javascript


Here we'll implement a for each function in our class and accept a callback that we can call on every key-value pair. Let's see how we can implement such a function − 

Example

forEach(callback) {
   for (let prop in this.container) {
      // Call the callback as: callback(key, value)
      callback(prop, this.container[prop]);
   }
}

You can test this using − 

Example

const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

myMap.forEach((k, v) => console.log(`Key is ${k} and value is ${v}`));

Output

This will give the output −

Key is key1 and value is value1
Key is key2 and value is value2

ES6 Maps also have a prototype method forEach that you can use similar to how we've used it here. For example,

Example

const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
 
myMap.forEach((k, v) => console.log(`Key is ${k} and value is ${v}`));

Output

This will give the output −

Key is key1 and value is value1
Key is key2 and value is value2

Monica Mona
Monica Mona

Student of life, and a lifelong learner

Updated on: 15-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements