6

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?

Community
  • 1
  • 1
Alfi Louis
  • 105
  • 1
  • 2
  • 5
  • Your last example probably doesn't work because your browser (which is what?) doesn't support it. –  Dec 04 '16 at 10:47
  • the feature was introduced in ECMAScript 2015 (ES6) if your system doesn't support that you cannot use this method. You can find an answer here https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable – Chandana Mar 21 '22 at 17:58

1 Answers1

6

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";
Algirdas
  • 196
  • 2
  • 7