
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- How do you Loop Through a Dictionary in Python?
- Loop through a Set using Javascript
- Loop through a hash table using Javascript
- Loop through array and edit string JavaScript
- Figuring out the highest value through a for in loop - JavaScript
- Iterating through a dictionary in Swift
- Loop through ArrayList in Java
- How to iterate through a dictionary in Python?
- How do we loop through array of arrays containing objects in JavaScript?
- Loop through an array in Java
- How to use for...in statement to loop through an Array in JavaScript?
- Loop through an index of an array to search for a certain letter in JavaScript
- Loop through a HashMap using an Iterator in Java
- How do you loop through a C# array?
- Recursively loop through an array and return number of items with JavaScript?

Advertisements