Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object key name with a variable [duplicate]

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?

like image 206
Alfi Louis Avatar asked Dec 04 '16 10:12

Alfi Louis


1 Answers

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";
like image 92
Algirdas Avatar answered Nov 05 '22 12:11

Algirdas