Dynamic Object Key in JavaScript

Anika Tabassum Era Oct 12, 2023
  1. Use Dot Notation to Check if It Can Set Dynamic Object Key in JavaScript
  2. Use Bracket Notation to Set Dynamic Object Key in JavaScript
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:

Use dot Notation to Check If It can Dynamically Set Object Key

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:

Use bracket Notation to Set Object Property Dynamically

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.

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Object