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
Selected Reading
Add elements to a Dictionary in Javascript
In JavaScript, there are multiple ways to add elements to a dictionary-like structure. You can use plain objects, custom dictionary classes, or the ES6 Map object.
Using Plain Objects
The simplest approach is using JavaScript objects as dictionaries. You can add key-value pairs using bracket notation or dot notation:
const dictionary = {};
// Using bracket notation
dictionary["key1"] = "value1";
dictionary["key2"] = "value2";
// Using dot notation (for valid identifiers)
dictionary.key3 = "value3";
console.log(dictionary);
{ key1: 'value1', key2: 'value2', key3: 'value3' }
Custom Dictionary Class
You can create a custom dictionary class with a put method for adding elements:
class MyDictionary {
constructor() {
this.container = {};
}
put(key, value) {
this.container[key] = value;
}
hasKey(key) {
return key in this.container;
}
display() {
console.log(this.container);
}
}
const myDict = new MyDictionary();
myDict.put("key1", "value1");
myDict.put("key2", "value2");
myDict.display();
console.log(myDict.hasKey("key1"));
console.log(myDict.hasKey("key3"));
{ key1: 'value1', key2: 'value2' }
true
false
Using ES6 Map
The ES6 Map object provides a more robust dictionary implementation with the set method:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
// Add new elements
myMap.set("key3", "value3");
myMap.set("key4", "value4");
console.log(myMap.has("key1"));
console.log(myMap.has("key3"));
console.log(myMap.get("key1"));
// Display all entries
for (let [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
true true value1 key1: value1 key2: value2 key3: value3 key4: value4
Comparison
| Method | Key Types | Performance | Built-in Methods |
|---|---|---|---|
| Plain Objects | Strings only | Fast | Limited |
| Custom Class | Strings only | Fast | Custom implementation |
| ES6 Map | Any type | Good | Rich API |
Conclusion
Use plain objects for simple string-key dictionaries, custom classes for specific functionality, or ES6 Map for advanced features like non-string keys. Map is recommended for complex dictionary operations.
Advertisements
