Dynamic Object Key in JavaScript
- Use Dot Notation to Check if It Can Set Dynamic Object Key in JavaScript
- Use Bracket Notation to Set Dynamic Object Key in JavaScript
Generally, we access the values or keys of a JavaScript object using dot notation. But there is a barrier that the dot notation works for predefined objects.
More elaborately, if we have an object with its content set, we can access them via the dot notation. However, if we need to set the key that refers to another value, then the dot notation cannot name the key as that referred value.
Here, we will see the difference in how a bracket notation with a variable key can dynamically set the object property and the dot notation cannot. In this regard, we will also infer that it is convenient to depend upon the bracket convention.
Use Dot Notation to Check if It Can Set Dynamic Object Key in JavaScript
As we have mentioned, the dynamic way of initializing a property cannot be performed by dot notation. Here, we will set an object j
with a key-value pair 'name': 'Rowan'
, we will try to assign the age
key as the name year
.
Let’s see what we get in the output.
var j = {'name': 'Rowan'};
var age = 'year';
j.age = 25;
console.log(j);
Output:
So, we did not get Rowan's
age as year: 25
; instead, we received age:25
. The dot notation thus cannot perform the dynamic way of setting an object key.
Use Bracket Notation to Set Dynamic Object Key in JavaScript
In the following example, we will use the bracket notation to rename our property age
to year
. And successfully, we will be able to perform the task.
Here, we will take the similar object j
with a key name
and its value. The difference is we will specify the age
key to have a different value year
.
var j = {'name': 'Rowan'};
var age = 'year';
j[age] = 25;
console.log(j);
Output:
So, calling upon the j[age]
, we get the key-value pair year:25
. This determines that the age
variable has been altered with the year
.
We can dynamically set the object key of a key-value pair depending on the bracket convention.