Considering the following code:
let mystr = 'abc';
let obj = {mystr: 'bla'};
console.log(obj);
Why does this output
{ mystr: 'bla' }
instead of
{ 'abc': 'bla' }
?
Computed object properties is what you are looking for.
let mystr = 'abc';
let obj = {[mystr]: 'bla'};
console.log(obj);
This is a mega duplicate
let mystr = 'abc';
let obj = {[mystr]: 'bla'};
console.log(obj);
Try the following:
let mystr = 'abc';
let obj = {};
obj[mystr] = "bla";
console.log(obj);
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);