This blog post will define the dynamic object key in JavaScript.
How to Set Dynamic Object Key in JavaScript?
In the ES6 version of JavaScript, developers can dynamically set the JavaScript property keys for their objects using the Bracket notation.
Syntax:
Follow the given syntax for setting a dynamic object key in JavaScript with bracket notation:
In the given syntax:
- “keyVar” is the variable name that stores the name of the key that will be added dynamically in the object.
- “keyName” is the name of a key that will be set dynamically in an object.
Example 1:
First, create a variable “newKey” for storing the name of the key “skill”:
Then, create an object “info”, with properties “name”, “age”, and “email”. Add another attribute of an object using the key “skill” that will dynamically add in an object:
Call the “console.log()” method by passing an object as an argument for printing all the properties of the object in a key-value pair:
Output
The above output shows that the dynamic key “skill” is successfully added and accessed in an object:
Example 2:
Let’s print the value of the key “skill” stored in the “info” object:
Output
The output indicates that the object “info” successfully accesses the value of the “newKey” variable and stores it as a dynamic key.
Conclusion
For adding an object key dynamically, use the bracket notation. First, store the key in a variable and then specify the variable name in bracket notation to set a key with value as a key-value pair in an object. This blog post defines the dynamic object key in JavaScript.