How to set an object key name via a variable in JavaScript?
Hello everyone! I just started learning JavaScript and encountered a problem when working with objects. I need to create an object where the key (property) name should be taken from a variable, not be a static string.
Here's what I'm trying to do: I have a variable `keyName` that contains the string "userName". I want to create an object where the key is the value of this variable, and the value is "John". I tried this:
```javascript
let keyName = "userName";
let obj = { keyName: "John" };
console.log(obj); // { keyName: "John" }
```
But as a result, the key is called `keyName`, not `userName`. That is, JavaScript uses the variable name as the key name, not its value. I understand that this is not what I need.
I need the key to be dynamic, that is, I want to get the object `{ userNa
No answers yet.
Log in to leave an answer
Blogs
Docker and TypeScript: Application Containerization for Developers