Dynamic Object Keys in JavaScript
- 1 minute read
In JavaScript, you might need to dynamically set an object key immediately after the object is declared.
Here is one way to go about doing that:
const dynamicProperty = `color`;
const dynamicValue = `red`;
let object = {
item: `T-Shirt`,
price: 20,
[dynamicProperty]: dynamicValue,
};
In the above example, item
and price
are static keys of object
.
However, a dynamic key of color
has been introduced and set to a value of red
.
Setting a dynamic key as a property in an object declaration statement is effectively a shorter way of setting a dynamic key like this:
const dynamicProperty = `color`;
const dynamicValue = `red`;
let object = {
item: `T-Shirt`,
price: 20,
};
object[dynamicProperty] = dynamicValue; // Notice how this requires a second statement after the declaration statement
Conclusion
Anyway, this is just a neat little trick that might make your code a bit cleaner! Enjoy!