Home >Web Front-end >JS Tutorial >How to Access JavaScript Object Keys Using Variables?
Accessing JavaScript Object Keys Via Variables
When building objects in JavaScript and storing keys in variables, you may encounter a situation where the object keys are set to the variable name ("key" in this case) instead of the variable's value.
Solution:
To resolve this issue, you can create the object first and then use square brackets ([]) to set the key dynamically from the variable:
var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj);
This method allows you to set the object key using the value stored in the variable.
ES6 Update (2021):
ES6 introduced computed property names, which provide a more concise syntax for dynamically setting object keys:
const yourKeyVariable = "happyCount"; const someValueArray= [...]; const obj = { [yourKeyVariable]: someValueArray, }
By using square brackets within object literals, you can now set object keys based on the value of variables, making your code more flexible and readable.
The above is the detailed content of How to Access JavaScript Object Keys Using Variables?. For more information, please follow other related articles on the PHP Chinese website!