Home >Web Front-end >JS Tutorial >How Can I Dynamically Assign Keys in JavaScript Objects?
Dynamic Key Assignment in JavaScript Objects
When constructing JavaScript objects, assigning keys dynamically, rather than statically, can be useful. However, simply using variables as key names can lead to unexpected behavior, resulting in "key" as the property key instead.
Solution 1: Object Initialization with Brackets
To specify the object key dynamically, you need to create an empty object first, then use square brackets ([]) to set the key-value pair:
var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj);
Solution 2: Computed Property Names (ES6)
ES6 introduced computed property names, which allow dynamic key assignment within object literal notation:
const yourKeyVariable = "happyCount"; const someValueArray= [...]; const obj = { [yourKeyVariable]: someValueArray, }
Example Fiddle:
Refer to this improved Fiddle for a practical demonstration: https://jsfiddle.net/Fr6eY/4/
The above is the detailed content of How Can I Dynamically Assign Keys in JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!