In the past, programmers could not utilize the variable as the property in an object. There was only one method to create the object, specify the value and pass the resulting object to execute the result. Now, JavaScript provides the facility to use the variable as the property of an object. Furthermore, you can also get the value of the defined property using the variable name. To do so, use the dot or the bracket notation.
This post has stated the method for finding an object id in an array of JavaScript objects.
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:
name: 'Hafsi',
category: 'JavaScript',
age: '25',
};
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',
name: 'Jack',
};
Then, invoke the log() method and pass the variable with dot notation as the argument of this method to get the value:
Output
You have learned about getting value in an object key using a variable referencing that key.
Conclusion
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.