How to Get/Fetch Value in an Object’s Key Using a Variable Referencing That Key?
To get/fetch the values in a defined object’s key with the help of a variable referencing that key, you can utilize the two methods. The first one uses bracket notations, and the second is dot notation. For the corresponding purpose, check out the examples stated below.
Example 1: Get Value in an Object Using Bracket Notations
To get the value of an object using bracket notations, first, declare a constant type object the assign data to the defined object:
Then, initialize a variable to store the value of the defined object:
Now, utilize the bracket notation with the name of the declared object and variable as the parameter of log() method to get the value of the key:
As a result, the value of the object using a variable will be fetched:
Example 2: Get Value in an Object Using Dot Notations
You can also get the value of the object with the help of dot notation. For that purpose, store the data in a constant type object:
country: 'United Kingdom',
Then, invoke the log() method and pass the variable with dot notation as the argument of this method to get the value:
You have learned about getting value in an object key using a variable referencing that key.
To get the value in an object’s key using the variable referencing that key, you can use the bracket notation and the dot notation method. In bracket notation, the “obj[variable]” can be utilized. Furthermore, the “obj.variable” refers to the dot notation. This post has stated the method for getting/fetching the value in a particular object key with the help of a variable referencing that key.