For over 5+ years we help companies reach their financial and branding goals. oDesk Software Co., Ltd is a values-driven technology agency dedicated

Gallery

Contacts

Address

108 Tran Dinh Xu, Nguyen Cu Trinh Ward, District 1, Ho Chi Minh City, Vietnam

E-Mail Address

info@odesk.me

Phone

(+84) 28 3636 7951

Hotline

(+84) 76 899 4959

Websites Development

Everything You Should Know about Javascript Dictionaries

Learn how to build and work with this genius data structure

Wait! Does Javascript have a Dictionary type now? Not exactly. At least, not yet.

But with its ever-so-flexible Object and ES6 Map types, creating a dictionary-like object for storing data as key-value pairs is only a matter of minutes.

This statement may seem a little strange to you if you’re coming from a background in a statically typed language. But with its dynamically typed nature, achieving this with Javascript is not a problem at all. So, in today’s article, let’s talk about how you can successfully create dictionaries in Javascript and access stored data using alternative data structures.

Create Dictionaries with Javascript Objects

Javascript Object type offers us enough flexibility to store data as key-value pairs as a standard dictionary does. But its versatility doesn’t end there. Object type also supports accessing stored data using keys, iterating through keys and values, and even using different data types as keys.

And it all starts with creating a new dictionary using Object. Here’s how we can do that.

let dict = {
    id: 123,
    name: "Anj",
    age: 28,
    registered: true
}

As an alternative way to create a dictionary, you can first initialize an Object instance and populate it with key-value pairs in the following manner.

//Create a new Object
let dict = new Object()

//Populate data
dict["id"] = 123
dict["name"] = "Anj"
dict["age"] = 28
dict["registered"] = true

We can take another step ahead and create an object with a null prototype. It removes all the methods inherited from Object.prototype. It suits us the best because these object methods are unnecessary for a dictionary. This includes methods such as hasProperty()hasOwnProperty()toString()valueOf() etc.

Here is how you can modify the Object creation step to get an object with a null prototype.

let dict = Object.create(null)

Javascript allows us to assign different data types—including string, integer, and float—for keys and values, even in the same dictionary.

let dict = {
    "color": "red",
    1: [12, 14, 90],
    1.2: 123,
} 

You can even store a Javascript method as a value in an Object-based dictionary.

const method = () => console.log("Hello");

let dict = {
    "method": method,
}

However, when storing keys of types other than string, Object implicitly converts them to string type before storing. For example, this is how Javascript has converted the keys of the above dictionary during its creation:

{
  '1': [ 12, 14, 90 ],
  color: 'red',
  '1.2': 123,
}

Access Data Using Keys

Being able to retrieve a particular key-value pair using the key is one of the most valuable features of the dictionary data structure. With the Javascript Object type, doing this is as easy as the following example shows.

let dict = {
    "color": "red",
    1: [12, 14, 90],
    1.2: 123
}   

dict["color"] //red
dict[1] //[12, 14, 90]
dict[1.2] //123

//Use key as a property 
dict.color //red

As this example shows, you can use any key as an index to retrieve the value associated with it. For keys of type string, you can access the value by considering the key as a property of the object.

Iterate Through Key-Value Pairs

Javascript Object type provides several methods to iterate through keys, values, or key-value pairs depending on the use case.

First, let’s see how to iterate through the keys in the dictionary using the Object.keys method.

for (const key of Object.keys(dict)) {
    console.log(key + ":" + dict[key])
}

Iterating through values of the dictionary follows the same pattern with the help of Object.values method.

for (const value of Object.values(dict)) {
    console.log(value)
}

We can also iterate over pairs of keys and values in the same loop using the Object.entries method.

for (const [key, value] of Object.entries(dict)) {
    console.log(key + ":" + value)
}

Remove a Key-Value Pair from the Dictionary

We can use Javascript’s delete operator to remove a key-value pair from an Object-based dictionary. For example:

let dict = {
    id: 123,
    name: "Anj",
    age: 28,
    registered: true
}

delete dict["registered"] 
dict //{ id: 123, name: 'Anj', age: 28 }

One downside to using the delete operator to remove a key-value pair is that it reduces the performance of your code. If you’re more concerned about the performance than completely removing the property from the dictionary, you can set its value to null or undefined to flag a “removed” property.

dict["registered"] = undefined
dict //{ id: 123, name: 'Anj', age: 28, registered: undefined }

Even though this method doesn’t entirely remove the property, it completes execution much faster than the delete operator.

With that, we have discussed the basics of creating dictionaries in Javascript with the help of its Object type. In the next section, let’s see how we can get a similar result using ES6 Maps.

Create Dictionaries with Javascript Maps

Javascript Maps, introduced in ES6, are another excellent alternative to use for creating dictionaries. In fact, Maps have an added advantage over regular Objects when it comes to functioning like dictionaries. We have listed some key benefits of using Maps over Objects for this use case below.

  • Keys in maps can be of any type. It includes objects in addition to the primitive and string types Objects accept as keys. And Maps preserve the initial type of the key without implicitly converting them to strings as Objects does.
  • A Map orders its key-value pairs in the order we inserted them. But the ordering in Objects is not as reliable and straightforward as Maps.
  • Maps have a “size” property that directly retrieves the number of stored key-value pairs. With Objects, we have to manually calculate the size with the help of Object.keys or a similar method.

So, how can we create dictionaries with Maps? Let’s find out.

//Create Map instance
let dict = new Map()

//Add key-value pairs
dict.set("id", 123)
dict.set("registered", true)

let person = {name: "Anj"}

//Add keys of different types
dict.set(1, [1, 2, 3, 5])
dict.set(person, "available")

This returns us a map with its key types preserved.

Map(4) {
  'id' => 123,
  'registered' => true,
  1 => [ 1, 2, 3, 5 ],
  { name: 'Anj' } => 'available'
}

Access Data Using Keys

ES6 Maps provides a dedicated “get” method to retrieve data based on keys. Here’s how we can use it to access stored key-value pairs.

dict.get("id") //123
dict.get("registered") //true
dict.get(1) //[1, 2, 3, 5]
dict.get(person) //available

Iterate Through Key-Value Pairs

Maps type in Javascript is directly iterable. So, we don’t have to use an additional method like Object.keys to retrieve the set of key-value pairs stored in a map. Instead, we can use a for…of loop to iterate over data like the following code snippet shows.

for (const [key, value] of dict) {
    console.log(key + ": " + value)
}

Maps also provide separate entries(), keys(), and values() functions to iterate over keys and values in different ways depending on the use case.

for (const [key, value] of dict.entries()) {
    console.log(key + ": " + value)
}

for (const key of dict.keys()) {
    console.log(key)
}

for (const value of dict.values()) {
    console.log(value)
}

Remove a Key-Value Pair from the Dictionary

Again, Maps have a dedicated method for deleting a stored key-value pair. It returns true if the delete operation completes and false otherwise.

dict.delete(person) //true

dict //Map(3) { 'id' => 123, 'registered' => true, 1 => [ 1, 2, 3, 5 ] }

Additional Dictionary Operations with Maps

In addition to what we discussed so far, Maps supports several more methods that allow us to interact with dictionaries. For example, we can use the following has method to check whether the dictionary contains a specific key.

dict.has("dog") //false
dict.has("id") //true

Get the size of the dictionary using size:

dict.size

Conclusion

Even though Javascript doesn’t have an in-built Dictionary data type, its Object and Map types can behave similarly to dictionaries in languages like Python. In today’s tutorial, we talked about using these alternative types to store and access key-value pairs in Javascript as a standard dictionary does.

So, next time, when you’re looking for something that works like a dictionary to solve a problem, you can choose one of the two options we provided here depending on your requirements.

Source: livecodestream

Author

oDesk Software

Leave a comment