The original question highlights a common challenge faced when constructing objects in JavaScript, where the desired key is stored in a variable. Using the variable as the key directly within the object literal results in the key being set as "key" instead of the desired variable value.
To address this issue, the solution provided suggests creating the object first and then using the bracket notation to set the key dynamically. By placing the variable name in brackets, JavaScript interprets it as a computed property, dynamically assigning the variable's value as the key.
var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj);
In this approach, the object obj is created with an empty key. Then, the variable key is used as the computed property, setting the key to the desired value. Finally, the object is pushed into the array.
An alternative method introduced in ES6 is using computed property names. This feature allows you to dynamically compute the property names of an object using the square bracket syntax:
const yourKeyVariable = "happyCount"; const someValueArray= [...]; const obj = { [yourKeyVariable]: someValueArray, }
In this code, the obj object is created with a computed property name where the variable yourKeyVariable determines the key. This approach provides a concise and flexible way to dynamically set object keys in JavaScript.
The above is the detailed content of How Can I Dynamically Assign Keys to JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!