0

Considering the following code:

let mystr = 'abc';
let obj = {mystr: 'bla'};
console.log(obj);

Why does this output

{ mystr: 'bla' }

instead of

{ 'abc': 'bla' }

?

kramer65
  • 50,427
  • 120
  • 308
  • 488

4 Answers4

3

Computed object properties is what you are looking for.

let mystr = 'abc';
let obj = {[mystr]: 'bla'};
console.log(obj);
bugs
  • 14,631
  • 5
  • 48
  • 52
1

This is a mega duplicate

let mystr = 'abc';
let obj = {[mystr]: 'bla'};
console.log(obj);
Sampgun
  • 2,822
  • 1
  • 21
  • 38
0

Try the following:

let mystr = 'abc';
let obj = {};
obj[mystr] = "bla";
console.log(obj);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
0

let obj = {mystr: 'bla'}; will be processed by javascript considering the name of the key as mystr as object is declared with {key: value} but if you need to render the value of variable as a name of the key then you need to use square notation like obj[mystr] = 'bla'; as this will enforce the JavaScript runtime to render the value of mystr as a name of the key.

let mystr = 'abc';
let obj = {};
obj[mystr] = 'bla';
console.log(obj);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62