How to create a JavaScript Dictionary and add key value pairs

Dictionary objects are very useful in any programming language. In this article let’s see how to create a JavaScript Dictionary and add key-value pairs.

Many programming languages like C# and Java have built-in functionality to create dictionary items and add key-value pairs but JavaScript doesn’t natively include a type called “Dictionary”.

How to create a JavaScript Dictionary and add key value pairs

Creating a Dictionary in JavaScript

As discussed earlier there is no built-in type called Dictionary in JavaScript. However, it’s very easy to create a hashtable/dictionary in JavaScript.

Step 1: Create a new JavaScript Object

We can create any data type of key-value pairs in JavaScript. In the below code we will see how to access these dictionary values.

var dict = new Object();

// or the shorthand way
var dict = {};

You can also initialize the Dictionary with Key/Value pairs when creating it if you are using the shorthand method.

var dict = {
FirstName: "Mark",
"one": 1,
1: "numeric one"
};

Step 2: Read the Dictionary objects

Step 1 will create a dictionary and also has key-value pairs in it. Now in order to populate the values of the object, we can use the below code.

// using the Indexer
dict["one"] = 1;
dict[1] = "numeric one";

/ / direct property by name
// because it's a dynamic language
dict.FirstName = "Mark";

Iterating key/value pairs in JavaScript

In order to iterate the dictionary objects in JavaScript, you could use a simple “for” loop as shown below.

for(var key in dict) {
var value = dict[key];

// do something with "key" and "value" variables

}
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like