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' }

?

0

4 Answers 4

3

Computed object properties is what you are looking for.

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

Sign up to request clarification or add additional context in comments.

Comments

1

This is a mega duplicate

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

Comments

0

Try the following:

let mystr = 'abc';
let obj = {};
obj[mystr] = "bla";
console.log(obj);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.