Sometimes, we want to create an associative array in JavaScript literal notation.
In this article, we’ll look at how to create an associative array in JavaScript literal notation.
How to create an associative array in JavaScript literal notation?
To create an associative array in JavaScript literal notation, we can use maps.
For instance, we write
const arr = new Map([
["key1", "User"],
["key2", "Guest"],
["key3", "Admin"],
]);
const res = arr.get("key2");
console.log(res);
to create a map by calling the Map
constructor with a nested array of key-value pair arrays.
Then we calk get
to get the value with the key 'key2'
.
So res
is 'Guest'
.
Conclusion
To create an associative array in JavaScript literal notation, we can use maps.