How to Set an Object Key using a Variable in JavaScript
Table of Contents
The beautiful thing about JavaScript is how flexible it is.
One thing you might need to be able to do is set a key of an object using a variable.
This is usually when you don't know the key name until runtime, and therefore cannot hardcode it.
In this post, we'll learn how you can set the key of an object using a variable in JavaScript.
How to set an object key using a variable
To start, let's create an object.
JAVASCRIPTconst object = {};
console.log(object);
BASH{}
Now let's create a variable to set our new key:
JAVASCRIPTconst key = "key";
const value = "value";
console.log(key);
console.log(value);
BASHkey
value
In the end, we want an object that looks like this:
JAVASCRIPT{
key: "value"
}
To do this, you will need to use a computed property name. The syntax for this looks like this:
JAVASCRIPTconst key = "key";
const value = "value";
const object = {
[key]: value
};
console.log(object);
BASH{ key: 'value' }
Alternatively, you can also just create an empty object, then assign it the dynamic key-value pair:
JAVASCRIPTconst key = "key";
const value = "value";
const object = {};
object[key] = value;
console.log(object);
BASH{ key: 'value' }
Conclusion
In this post, we learned how to set an object's key with a dynamic key-value, such as from a variable.
Simply use a computed property name, and you're good to go!
Thanks for reading!
- Getting Started with Solid
- Getting Started with Express
- How to deploy a .NET app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue