Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Loop through a Dictionary in Javascript
In JavaScript, a dictionary (or object) stores key-value pairs. There are several ways to loop through these pairs depending on whether you're working with plain objects, ES6 Maps, or custom implementations.
Method 1: Using for...in Loop (Plain Objects)
The for...in loop is the traditional way to iterate through object properties:
const dictionary = {
key1: "value1",
key2: "value2",
key3: "value3"
};
for (let key in dictionary) {
console.log(`Key: ${key}, Value: ${dictionary[key]}`);
}
Key: key1, Value: value1 Key: key2, Value: value2 Key: key3, Value: value3
Method 2: Using Object.entries()
Object.entries() returns an array of key-value pairs, which you can iterate with forEach():
const dictionary = {
name: "John",
age: 30,
city: "New York"
};
Object.entries(dictionary).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
name: John age: 30 city: New York
Method 3: Custom forEach Implementation
You can implement a forEach function in a custom class to iterate through internal data:
class MyMap {
constructor() {
this.container = {};
}
put(key, value) {
this.container[key] = value;
}
forEach(callback) {
for (let prop in this.container) {
callback(prop, this.container[prop]);
}
}
}
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}`));
Key is key1 and value is value1 Key is key2 and value is value2
Method 4: Using ES6 Map.forEach()
ES6 Maps have a built-in forEach() method that works similarly:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
myMap.forEach((value, key) => console.log(`Key is ${key} and value is ${value}`));
Key is key1 and value is value1 Key is key2 and value is value2
Comparison
| Method | Use Case | Performance | ES6 Support |
|---|---|---|---|
for...in |
Plain objects | Fast | All versions |
Object.entries() |
Modern approach | Good | ES2017+ |
Map.forEach() |
ES6 Maps | Excellent | ES6+ |
Conclusion
Use for...in for simple object iteration, Object.entries() for modern JavaScript, and Map.forEach() when working with ES6 Maps. Choose based on your data structure and browser support needs.
