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
Search Element in a Dictionary using Javascript
In JavaScript, searching for elements in a dictionary (key-value pairs) can be accomplished using custom dictionary implementations or built-in ES6 Map objects. Both approaches provide efficient key-based lookups.
Custom Dictionary Implementation
Here's how to implement a get method that searches for a given key in a custom dictionary:
get(key) {
if(this.hasKey(key)) {
return this.container[key];
}
return undefined;
}
JavaScript objects are implemented like dictionaries internally, providing optimized key-value operations. This makes direct property access very efficient for search operations.
Complete Custom Dictionary Example
class MyMap {
constructor() {
this.container = {};
}
put(key, value) {
this.container[key] = value;
}
hasKey(key) {
return this.container.hasOwnProperty(key);
}
get(key) {
if(this.hasKey(key)) {
return this.container[key];
}
return undefined;
}
}
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
console.log(myMap.get("key1"));
console.log(myMap.get("key2"));
console.log(myMap.get("key3"));
value1 value2 undefined
Using ES6 Map Object
ES6 provides a built-in Map object with a get() method for efficient key-based searches:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
console.log(myMap.get("key1"));
console.log(myMap.get("key2"));
console.log(myMap.get("key3"));
value1 value2 undefined
Alternative Search Methods
For plain JavaScript objects, you can also use direct property access or bracket notation:
const dictionary = {
"key1": "value1",
"key2": "value2"
};
// Direct property access
console.log(dictionary.key1);
console.log(dictionary["key2"]);
// Safe search with fallback
console.log(dictionary["key3"] || "Not found");
value1 value2 Not found
Comparison
| Method | Performance | Key Types | Use Case |
|---|---|---|---|
| Custom Dictionary | Fast | String keys only | Learning/custom logic |
| ES6 Map | Optimized | Any type | Production code |
| Plain Object | Fastest | String/Symbol | Simple dictionaries |
Conclusion
Use ES6 Map for complex key-value operations, plain objects for simple string-based dictionaries, and custom implementations when you need specialized behavior. All methods provide efficient O(1) average-case search performance.
