DEV Community

Cover image for How to Use JavaScript Dictionary Like a Pro
Raja MSR
Raja MSR

Posted on • Updated on • Originally published at rajamsr.com

How to Use JavaScript Dictionary Like a Pro

If you are looking for a solution to store your key-value pairs like settings, and lookup data then a JavaScript dictionary is the right choice for you! 

The dictionary is a data structure that stores data in key-value pairs. It is used to store and retrieve data in an efficient way. JavaScript dictionary, allows you to store and retrieve data using key-value pairs. In contrast to arrays, which store data in a linear order, dictionaries in JavaScript allow you to access data using a unique key rather than an index. This makes dictionaries ideal for storing data that must be accessible fast and readily, such as a user database or a product list.

In this blog post, we will explore the following:

  • Create a dictionary in 3 different ways
  • Add key value pair to the dictionary
  • Update value for a key
  • Accessing items from the dictionary
  • Iterating over a dictionary with 3 different approaches
  • Get all dictionary keys
  • Get all values from a dictionary
  • Get the length of dictionary keys
  • Check whether a key exists in the dictionary
  • Delete an item from the dictionary

Let’s dive deep.

JavaScript Dictionary - Overview

Creating a Dictionary in JavaScript

Unlike other strongly typed programming languages like C#, and Java, JavaScript does not have any native data type of Dictionary. However, we can create custom Dictionary kinds of JavaScript objects. The dictionary allows you to store data in key-value format.

There are multiple ways to create a dictionary in JavaScript. In this blog post, we will see 3 different approaches:

1. Using the object literal notation

Using an object literal is the most common and simple way to create a dictionary. You can create an empty dictionary by using { } or you can add key-value pairs to it by using the object literal syntax. 

Here is a JavaScript dictionary example:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}
console.log(languages)
// Output: { EN: 'English', ES: 'Spanish', TA: 'Tamil' }

Enter fullscreen mode Exit fullscreen mode

JavaScript Dictionary

2. Using the Map() object

The Map() is one of the Non-Primitive Data Types in JavaScript. Using the Map() object you can create a dictionary that can hold any type of value. You can create an empty map by using the new Map(). You can add key-value pairs to the map by using the set() method. 

For example, create a dictionary using Map() object:

const languages = new Map()
languages.set('EN', 'English');
languages.set('ES', 'Spanish');
languages.set('TA', 'Tamil');
Enter fullscreen mode Exit fullscreen mode

Not just with JavaScript String, you can use any type as the value in the dictionary as shown in the following example:

// Empty dictionary object 
let lookupData = {}

// Dictionary with single key-value pair 
let name = { "name": "John Doe" }

// Dictionary with multiple key-value pairs 
let person = { "name": "John Doe", "age": 25 }

// Dictionary with numeric keys 
let days = { 1: "Monday", 2: "Tuesday", 3: "Wednesday" }

// Dictionary with boolean values 
let status = { "isActive": true, "hasAccess": false }

// Nested dictionary object 
let people = { "person": { "name": "John Doe", "age": 25 } }

// Dictionary with array as value 
let fruits = { "fruits": ["apple", "banana", "orange"] }

// Dictionary with function as value
let functions = { "calculate": function (a, b) { return a + b; } }

// Dictionary with undefined and null values 
let edgeCases = { "name": undefined, "age": null }
Enter fullscreen mode Exit fullscreen mode

3. Using The Object.create() Method

This method allows you to create a dictionary by inheriting properties from another object. 

For example:

let languages = Object.create({});
languages.EN = 'English';
languages.ES = 'Spanish';
languages.TA = 'Tamil';
console.log(languages)
Enter fullscreen mode Exit fullscreen mode

Though we can create JavaScript dictionaries in different ways, I followed the first way to create a dictionary in this article. Let’s explore different JavaScript dictionary methods to manipulate it.

I would recommend you also follow the same and consistent way to create a dictionary across application code.

Adding key-value pair to a dictionary

So dictionary is created, let’s see how to add, modify and remove key-value pairs from the dictionary. The key names should be unique in the dictionary. Of course, key names are case-sensitive.

You can add items to a dictionary by using the square bracket notation. You can use the set() method if you created your dictionary using Map() method. 

For example, the following example shows how to add new key-value pair using bracket notation:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

languages['FR'] = 'French'
console.log(languages)
// Output: { EN: 'English', ES: 'Spanish', TA: 'Tamil', FR: 'French' }
Enter fullscreen mode Exit fullscreen mode

You can use the following dot notations as well to add key-value pair:

Updating value of a dictionary key

You can update the value in a dictionary by using the square bracket or dot notation method. For example:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

languages['EN'] = 'English (US)'
console.log(languages)
// Output: { EN: 'English (US)', ES: 'Spanish', TA: 'Tamil' }
Enter fullscreen mode Exit fullscreen mode

In this example, the “English” value is updated with the value “English (US)” using the unique key ‘EN’.

Access dictionary items in JavaScript

You can access dictionary-stored key-value pairs by using the square bracket notation, the get() method (if created using the Map() method), the for…in loop, or the for…of loop. 

The following dictionary object is used to show the dictionary iteration example:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

// Read dictionary value using key
console.log(languages['ES'])
// Output: "Spanish"
Enter fullscreen mode Exit fullscreen mode

You can use the following JavaScript dictionary methods and properties to manipulate dictionary object.

Iterating over a dictionary

Because the dictionary is built with Objects, we can quickly iterate through its keys. There are many ways for iterating over the dictionary object. Each method has its own set of benefits and drawbacks.

In this section, we will look at 3 methods for iterating through a dictionary object.

1. Using the for...in loop

This is one of the most common and easy ways to iterate over a dictionary. It allows you to access the keys of the dictionary, one at a time. Here is an example of how to use for loop in dictionary to get key and value:


for (let key in languages) {
  console.log(`${key}=${languages[key]}`);
}
// Output: 
EN=English
ES=Spanish
TA=Tamil
Enter fullscreen mode Exit fullscreen mode

2. Using the for...of loop

The Object.entries() is one of the object methods. Using this method along with the for…of loop, but it allows you to access the values of the dictionary as an array. For example:


for (let key of Object.entries(languages)) {
  console.log(key);
}

// Output: 
[ 'EN', 'English' ]
[ 'ES', 'Spanish' ]
[ 'TA', 'Tamil' ]
Enter fullscreen mode Exit fullscreen mode

3. Using the entries() method

for (let [key, value] of Object.entries(languages)) {
  console.log(`${key}=${value}`);
}

// Output: 
EN=English
ES=Spanish
TA=Tamil
Enter fullscreen mode Exit fullscreen mode

Get all dictionary keys and print

Keys are the primary means of accessing values in a JavaScript dictionary object. Dictionary keys can be any JavaScript type, including strings, numbers, and symbols. 

Here’s an example of how to create a dictionary object with string keys:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

console.log(Object.keys(languages))
// Output: ["EN", "ES", "TA"]
Enter fullscreen mode Exit fullscreen mode

In this example, the keys are ‘EN’, ‘ES’, and ‘TA’. The corresponding values are ‘English’, ‘Spanish’, and ‘Tamil’ for those keys. Using JavaScript Object.keys() method you can access all dictionary keys.

Get all dictionary values

To retrieve the values of a JavaScript dictionary object, you can use the Object.values() method. This method return values as an array.

Here’s an example:

const languages = {
    'EN': 'English',
    'ES': 'Spanish',
    'TA': 'Tamil'
}

console.log(Object.values(languages));
// Output: [ 'English', 'Spanish', 'Tamil' ]
Enter fullscreen mode Exit fullscreen mode

JavaScript dictionary size or length of dictionary

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

console.log(Object.keys(languages).length)
// Output: 3
Enter fullscreen mode Exit fullscreen mode

In this example, the Object.keys() method returns an array of the keys in the dictionary object (‘EN’, ‘ES’, and ‘TA’). The length property of that array is used to determine the length of the dictionary object. In this case,  there are three keys, so the length is 3.

JavaScript check dictionary contains a key

To check if the key is in the dictionary object, you can use the includes() or the hasOwnProperty() method. Here’s an example using the includes():

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

console.log(Object.keys(languages).includes('EN'));
// Output: true

console.log(Object.keys(languages).includes('en'));
// Output: false

Enter fullscreen mode Exit fullscreen mode

In this example, the Object.keys() method will return dictionary keys as an array. You can use the JavaScript includes() Method to check if the ‘EN’ keys exist in the dictionary object.

In JavaScript, string values are case-sensitive. So the dictionary key ‘en’ search returns false because the actual key is in capital letters.

There are two ways to search dictionary keys in a case-insensitive manner. Convert both keys and search text to JavaScript Lowercase or convert the keys and text to JavaScript Uppercase before searching.

JavaScript dictionary get value by key

To retrieve the value associated with a specific key in a JavaScript dictionary object, you can use the bracket notation or the get() method. Here’s an example using the bracket notation:

const languages = {
  'EN': 'English',
  'ES': 'Spanish',
  'TA': 'Tamil'
}

console.log(languages['EN']);
// Output: "English"

console.log(languages.EN);
// Output: "English"
Enter fullscreen mode Exit fullscreen mode

JavaScript dictionary delete key

The delete operator can be used to remove a key-value pair from a JavaScript dictionary object. Here’s an example of how to use the delete operator:

const languages = {
    'EN': 'English',
    'ES': 'Spanish',
    'TA': 'Tamil'
}

delete languages['TA']
console.log(Object.values(languages));
// Output: [ 'English', 'Spanish' ]
Enter fullscreen mode Exit fullscreen mode

In this example, the language Tamil was deleted from the dictionary using the key ‘TA’.  If we print the dictionary object “languages”, it will print the remaining key-value pairs. 

Conclusion

In conclusion, JavaScript does not have a native dictionary data type. However, we can create JavaScript dictionary objects. The dictionary data structure allows you to store and retrieve data using key-value pairs. They are especially useful when you need rapidly and readily accessible data. 

We explored how to create a dictionary and add or modify dictionary values. There are multiple methods for iterating over a dictionary. You can use the for…in loop, the for…of loop, and the Object.entries() methods. 

You can check the dictionary length by counting its keys. Using the array includes() method you can check whether the key already exists in a dictionary. The JavaScript delete operator can help you to remove a key-value pair from a dictionary object.

How you are going to use JavaScript dictionary object?

Top comments (4)

Collapse
 
artydev profile image
artydev

Thank you

Collapse
 
manchicken profile image
Mike Stemle

I’m not quite sure why you say JavaScript lacks a native dictionary type. It has two of them, and you even discuss them in your piece.

There are so many ways to search JavaScript objects by key and value. Take a look at the lodash module in npm.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Actually 3, the author failed to mention WeakMap

Collapse
 
manchicken profile image
Mike Stemle

Sure, but WeakSet can’t be enumerated, so I can see skipping it on a beginner tutorial on Dictionaries. It’s OK to skip over advanced, or more domain-specific, stuff in a beginner tutorial.