JavaScript

How to create a dictionary in JavaScript with key-value pairs?

Most of the time, the databases are used for storing a large amount of data for using it later on or for saving the state of the application but there comes a need to store the data locally inside the code to use it later. Therefore, programming languages have some standard data types which are really helpful in achieving such functionality without using the database.

Need of key-value pairs

So for this purpose, JavaScript uses arrays and Objects to store some records inside the code. Unlike other programming languages, JavaScript has no exact type to be called a Dictionary, but it does have a diverse type which is called Object in JavaScript. JavaScript’s Object is quite flexible as you can use it dynamically wherever you want. Most of the time objects are widely used for the data as they can be easily utilized later in the code.

Object

Objects are also the same as Dictionaries in other programming languages as the Objects also consist of the key Value pairs and the dictionaries are also based on this key-value pair formation structure. You can assign a key against a specific value to access it later on.

In this article, we are going to see how we can create dictionaries in JavaScript and how we can easily manipulate some data into them with the help of some examples.

How to create a Dictionary/Object in JavaScript

Because Dictionaries are not the traditional data types of JavaScript hence we use them the same way to create the dictionaries as we declare the objects and initialize some values to them.
Let’s take an example for creating the object.

Example

let myFirstObject = new Object();

// or the shorthand way
let myFirstObject = {
  firstName: 'Mark',
  lastName: 'Fonso',
  age: 20
}

console.log('the type of the variable is :',typeof(myFirstObject), 'and its values are :', myFirstObject)

There are two basic ways through which you can create an object in JavaScript, the first one is by declaring the name of the object which in our case is “myFirstObject” and then creating its instance by initializing a new Object().

The second way is considered as a shorthand method which is to simply declare the name of the object and assign it some key-value pairs to make the interpreter understand that yes it is an object.

Output:

Here you can see that the type of object is Object as I said that there is no traditional data type called object hence JavaScript objects are treated as objects in some cases.

Let’s take another example of creating a new Object in below example

Example

let expObject = {
  firstName : "John Doe",
  "Ten": 10,
  10: "Any Integer",
  "experience": 0
};

console.log('Type: ',typeof(expObject), '\n','Values: ', expObject)

Here in the above example, we have created and initialized a new object with the name expObject and console logged it into the terminal while checking its data type and displaying the values inside it.

As you can see in the above output screen that the type is being displayed as an Object while its values are also being displayed in the output terminal as we expected.

Assigning Values to the object keys

We have successfully created our object, now let’s check out the values by using the key names in the below example;

This may be accomplished by utilizing the Object’s Indexer property to set the values, or by using it directly as if it were a normal property on the object. The Key values can be any object, not just strings:

let expObject = {
  firstName : "John Doe",
  "Ten": 10,
  10: "Any Integer",
  "experience": 0
};

expObject["Ten"] = 20;
expObject[10] = "Twenty";
 
expObject["experience"] = 22;

console.log('Type: ',typeof(expObject), '\n','Values: ', ExpObject)

// Assigning property directly
dict.firstName = "John Doe";

Here in the above example, we have created an object and later on, we have assigned the values exclusively to the specific properties or keys of the object by using the indexer method.

Output

You can now clearly see in the above provided output screen that the values have been updated in the object.

Assigning values to the object using the dot operator (Direct Assignment)

Till now we have discussed how we can create objects and how we can assign some values to the properties of the object using the indexer method, here in the below example we will see how we can use a dot operator to assign some values to the properties of the object.

Example

let expObject = {
  firstName : "John Doe",
  "Ten": 10,
  10: "Any Integer",
  "experience": 0
};

expObject.Ten = 20;
expObject.experience = 10;
 
expObject.firstName = 'Mark Huggy';

console.log('Type: ',typeof(expObject ), '\n','Values: ', expObject )

Here in the above example we are creating a object and later on we are assigning some values to its properties using dot operator or you can say a direct assignment in other words.

You can see that the above-highlighted values are updated in the object.

Iterating key-value pairs of the object

Now we will discuss about iteration of the key-value pairs.

Example
Here in the following example, we will create an object and then we will loop through each key of the object and display the value against each key of the object:

let expObject = {
  firstName : "John Doe",
  "Ten": 10,
  10: "Any Integer",
  "experience": 0
};
for(let key in expObject ) {
  let value = expObject [key];
  console.log(value);
 
}

Output

The values are being displayed against each key with the help of a for loop

Direct Access to Key/Value Pairs

Same as direct Assignment, We can also directly access the values of the object using a dot operator and assign it to some other variable for later usage. Let’s see in the below example:

 let expObject  = {
  firstName : "John Doe",
  "Ten": 10,
  10: "Any Integer",
  "experience": 0
};

let first_name = expObject.firstName;

expObject.firstName = "Mark Christonson";

console.log('Old name :',first_name, '\nNew Name: ', expObject.firstName )

Here in the above example, we have created an object and later, we have assigned its old firstName value to the first_name variable and updated the value of the firstName by using the direct assignment method. Later on, we have displayed both the old and the new values in the screen

Output:

You can see both the old and the new name fields in the above output screen.

Conclusion

Dictionary is not the traditional data type of the JavaScript programming language, but the objects can be treated as dictionaries in some cases. You can create an object through two different ways, one is to declare it and initialize it using the new Object() method and the second one is the shorthand way by simply declaring and assigning some key-value pairs to it. In this article, we went through both methods in detail and we have discussed how we can assign and retrieve values using direct assignment and indexer methods.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.