How to Create Dictionary and Add Key-Value Pairs in JavaScript
This article explains how to create a dictionary in JavaScript and add key-value pairs to it.
As of now, JavaScript does not contain a native dictionary data type.
However, objects in JavaScript are highly versatile and may generate key-value pairs. These things are fairly similar to dictionaries and operate similarly.
Dictionaries are often utilized since each value saved has a unique key, and with these keys, their associated values may be retrieved. It gives a lot of freedom in reading and storing data.
Use Object Literals to Create a Dictionary in JavaScript
A dictionary may be generated using two ways. The object literal method uses the new
keyword.
However, we concentrate on the former.
It is because it is quite probable that you have used dictionaries previously, and this approach follows a familiar syntax.
Syntax using Object literals:
Use the syntax below to generate an empty JavaScript dictionary, where dict
is the object’s name.
var dict = {};
Initializing and constructing a dictionary:
var dict = {
Name: 'Shiv',
Age: 21,
Job: 'Freelancer',
Skills: 'JavaScript',
};
console.log(dict);
Output:
{
Age: 21,
Job: "Freelancer",
Name: "Shiv",
Skills: "JavaScript"
}
Add Key-Value Pairs in JavaScript
Key-value pairs may be added when building a JavaScript dictionary; however, these techniques can also add values.
Code to add items:
var [key] = value;
The key
stands for the identifier of the unique key, and the value
is the corresponding data the key relates to.
If the dictionary already includes the name you have supplied as the key, you could either change your key or use the following code to update the value.
dict.key = new_value;
Accessing things is likewise fairly basic; the following code may be used.
var value = dict.key;
The value
relates to the variables you use to hold the accessed key’s value.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Dictionary in Javascript</title>
</head>
<body style="text-align: center;">
<h1>Dictionary in Javascript</h1>
<p>
var dict = { <br />
"key_1" : 1 , <br />
"key_2" : "2", <br />
"key_3" : 3 <br />
}; <br />
</p>
<button onClick="funcn()">Add new Key-Value Pairs</button>
<p id="demo"></p>
<!-- Script to create dictionary
and add key-value pairs -->
<script>
function funcn() {
var dict = {
key_1: 1,
key_2: "2",
key_3: 3,
};
dict.new_key = "new_value";
dict["another_new_key"] = "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:
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.
LinkedIn