
How to Set Object Keys by Variables in JavaScript
In order to use variable names as object keys, you need to make use of bracket notation:
const key = 'showTopProducts';
const filters = { ... };
filters[key] = true;
Copied to clipboard!
It is called a property accessor, that provides a way to access the properties of an object.
If you are using ES6 and above, you can also use bracket notation right inside an object:
const key = 'showTopProducts';
const filters = {
[key]: true
};
console.log(filters);
// The above console.log will output:
{ showTopProducts: true }
Copied to clipboard!

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Resources:
π More Webtips
Master the Art of Frontend
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions