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.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Javascript

Javascript URLEncode

Let us take a look at what would be the best approach for Encoding URL using Javascript. There are basically 3 Javascript URLEncode methods available. Types of Javascript URLEncode escape()…
View Post
How To Get File Size In Python

How to Get File Size in Python?

Table of Contents Hide Python get file sizeMethod 1: Get file size using os.path.getsize()Method 2: Get file size using os.stat()Method 3: Get file size using seek() and tell()Method 4: Get…
View Post