Using a dictionary data structure in JavaScript
If you're looking for a dictionary data structure in JavaScript, you can use the Map
object. It was introduced in ECMAScript 6. It is very similar to the implementation of a dictionary data structure that you would find in other programming languages.
Getting a value from a Map
A Map
doesn't contain any keys upon creation. It will only contain what we explicitly put into it using the set
function.
const dictionary = new Map();
dictionary.set("Apple", "A fruit and a brand.");
console.log(dictionary.get("Apple")); // outputs "A fruit and a brand."
Map size
The number of items in a Map can be retrieved from its size
property.
console.log(dictionary.size); // 1
Map entry checking
We can check if a Map
contains a key using the has
function.
console.log(dictionary.has("Apple")); // true
Deleting from a Map
We can delete an entry from a Map
using the delete
function.
dictionary.delete("Apple")
console.log(dictionary.size); // 0
Adding objects and arrays to a Map
We can add objects or arrays to a Map
entry.
dictionary.set('Mario', { color: "Red", sibling: "Luigi" });
console.log(dictionary.get("Mario")); // { color: "Red", sibling: "Luigi" }
dictionary.set('Toad', ['Rainbow Road', 'Shy Guy Falls', 'Yoshi Circuit']);
console.log(dictionary.get("Toad")); // ['Rainbow Road', 'Shy Guy Falls', 'Yoshi Circuit']
Map versus regular objects
A Map
is a JavaScript object with special properties. It tends to perform better in situations that involve the frequent addition and deletion of key-value pairs. Regular objects are not optimized for this.
Map keys versus object keys
One of the Map
object's special properties is that the keys of a Map
can be any type of value, including functions and objects. This is unlike regular objects in JavaScript which cannot have any object as a key. Regular objects can only have string, number, or symbol keys.
const driver = { name: "Luigi", color: "Green" };
const kart = { type: "Sport Bike", tires: "Sport" };
const dictionary = new Map();
dictionary.set(driver, "1st place");
dictionary.set(kart, "No damage");
console.log(dictionary.get(driver)); // 1st place
console.log(dictionary.get(kart)); // No damage
console.log(dictionary.get({})); // undefined
The last output will return undefined because the empty object {}
does not reference the driver
or kart
object keys that are in the Map
.
Map iteration versus object iteration
A Map
is directly iterable. The Map
object will iterate entries, keys, and values in the order that they were entered. The items in the Map
will be output in the order that they were inserted.
const dictionary = new Map();
dictionary.set("Yoshi", "2nd Place");
dictionary.set("Toad", "3rd Place");
dictionary.set("Luigi", "1st Place");
dictionary.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Yoshi: 2nd Place
// Toad: 3rd Place
// Luigi: 1st Place
You can also iterate over the Map
using a for...of
loop to get the same output.
for (let [key, value] of dictionary) {
console.log(`${key}: ${value}`);
}
Regular JavaScript objects do not implement an iteration protocol. Therefore, they are not directly iterable using the forEach
or the for...of
loops. You could use Object.keys()
, Object.values()
, or Object.entries()
to iterate over a regular object's keys, values, or entries. However, the object itself is not directly iterable like the Map
is.
Keys and values of a Map
Just as with regular objects, you can also get the keys
and values
of a Map
.
const dictionary = new Map();
dictionary.set("Yoshi", "2nd");
dictionary.set("Toad", "3rd");
dictionary.set("Luigi", "1st");
for (let key of dictionary.keys()) {
console.log(key); // Yoshi, Toad, Luigi
}
for (let value of dictionary.values()){
console.log(value); // 2nd, 3rd, 1st
}
Conclusion
You can now confidently use the Map
object and data structure in JavaScript. If you are using a regular object for the frequent addition and deletion of key-value pairs, you will get better performance by converting that object into a Map
.