Open In App

How to create dictionary and add key–value pairs dynamically?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we will discuss how we can create a dictionary in JavaScript and add key-value pairs in it. Actually there is no ‘dictionary’ type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object  which will act as dictionary.

Syntax: Key can be a string , integer. If you just write key1 or any number, it will treat as a string.

var dict = { key1 : value1 , 
             key2 : value2 , 
             .... 
           };
  • Create empty dictionary
    var dict = {};
  • Adding Key-Value Pairs in Dictionary
    dict[new_key] = new_value;

    or
    If new_key is already present in the dictionary then the value of this will be updated to new_value.

    dict.new_key = new_value;
  • Accessing Key-Value Pairs
    var value = dict[key];

    or

    var value = dict.key;
  • Iterating the whole dictionary
    for(var key in dict) {
       console.log(key + " : " + dict[key]);
    }
    

Example:

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>Dictionary in Javascript</title>
    </head>
    <body style="text-align: center;">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <p>
            var dict = { <br />
            "geek" : 1 , <br />
            "for" : "2", <br />
            "geeks" : 3.5 <br />
            }; <br />
        </p>
  
  
        <button onClick="fun()">
            Add new Key-Value Pairs
        </button>
  
        <p id="demo"></p>
  
  
        <!-- Script to create dictionary 
                and add key-value pairs -->
        <script>
            function fun() {
                var dict = {
                    geek: 1,
                    for: "2",
                    geeks: 3.5,
                };
  
                dict.new_geeks = "new_value";
                dict["another_new_geeks"] = 
                "another_value";
  
                var to_show = "var dict = { <br>";
  
                for (var key in dict) {
                    to_show += '"' + key + '" : ' 
                    + dict[key] + "<br>";
                }
  
                to_show += " }; <br>";
  
                document.getElementById("demo")
                .innerHTML = to_show;
            }
        </script>
    </body>
</html>                    


Output:



Last Updated : 28 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads