In JavaScript, when constructing objects, you may encounter a situation where you want to dynamically set the key's value using a variable. However, by simply following common object initialization syntax, you will observe that the key is set to the variable's name rather than the intended value.
The following code snippet illustrates the issue:
var key = "happyCount"; myArray.push({ key: someValueArray });
Inspecting myArray after this operation reveals that the key for each object is "key" instead of the intended value stored in the key variable.
To resolve this issue, create the object before setting the key using the bracket notation []. This syntax allows you to dynamically set the key's value from a variable.
var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj);
Now, the created object will have the key set to the value of the key variable.
ECMAScript 2015 (ES6) introduced computed property names, a feature that allows for even more flexibility in defining object keys dynamically. This syntax uses square brackets [] to enclose the property name, which can be any valid JavaScript expression.
const yourKeyVariable = "happyCount"; const someValueArray = [...]; const obj = { [yourKeyVariable]: someValueArray, };
This code achieves the same result as the previous solution but uses the computed property names syntax, which is more concise and expressive.
The above is the detailed content of How Can I Dynamically Set Object Keys Using Variables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!