Open In App

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

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 , 
             .... 
           };

Example:




<!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:


Article Tags :