How to use a variable for a key in a JavaScript object literal?
To assign a key to a JavaScript object dynamically, utilize the computed property names feature by using square brackets [ ]
:
This approach was introduced in ECMAScript 2015 (ES6) and allows for more dynamic code, making it ideal for cases envolving variable data.
ES6: A step to dynamic object literal keys
The old way: ES5 and earlier
Before ES6, if you wished to use a key from a variable, it required a bit more patient maneuvering:
The new way: Welcome ES6
ES6 brought along a cool new feature: computed property names. You can now set property keys dynamically directly in the object literal:
Now, doing newObj['.Dynamic']
gets you 'Now, we are dynamic!'
. Magic? No, it’s JavaScript!
Various flavors of property keys
ES6 gave us several options to name property keys:
- String:
{ "myKey": "Gotcha!" }
- Number:
{ 404: "Error" }
// Where did the page go? - Identifier:
{ validIdentifier: "Fine by me!" }
- Template literals:
{[`Key_${expression}`]: "I'm a mix!"}
The power of dynamic keys
Animating things dynamically
With animate
and similar functions, dynamic property names can bring your animations to life:
CSS on the go
Imagine changing CSS properties for DOM elements dynamically:
This makes for more responsive and interactive user experiences.
Was this article helpful?