I am trying to make an object which has one key name taken from a variable.
var key="KeyName"
var obj={
key:"value"
}
When I want to access the "KeyName" key,I can't because I have just created a key with the name "key" not "KeyName". I found a soution here :
JavaScript set object key by variable
var key="KeyName"
var obj={
[key]:"value"
}
But it doesn't work. What to do?
You can do it like this: first initialize the object and use brackets []
to set key value.
var obj = {};
var key = "KeyName";
obj[key] = "value";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With