3

i want to add or modify an object using property name that is a variable.

i found out that the way to use dynamic property names is using square brackets,

var x ="hi"

a = {
...a,
[x]:"hello"
}

above code works and object a has new property named "hi".

we can add a new property using a string property name like below.

a = {
...a,
"hiwithstring":"hello with string"
}

above code works fine as it is the normal way. even if we don't keep name in string quotes, js engine internally does that for us.

using string interpolation, we can include variables into string like below,

var x ="hiWithInterpolation"
 var propName = `${x}`
//now propName is "hiWithInterpolation".

now my question is why can't we use string interpolation to add dynamic property names like below ?

var x ="hiWithInterpolation"
a = {
...a,
`${x}`:"helloWithINterPolation"
}

above code doesn't work and throws Uncaught SyntaxError: Unexpected template string.

coudl someone explain why last example is failing ?

Ayyappa Gollu
  • 906
  • 7
  • 16

1 Answers1

3

You need a computed property name.

var x = "hiWithInterpolation";
a = {
    ...a,
    [`${x}`]: "helloWithINterPolation"
};
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392