Try:
let surveyTypes = [1,2];
let surveyDuration = {
[surveyTypes[0]]: 'first',
[surveyTypes[1]]: 'second'
}
In order to evaluate the key name, it must be inside brackets. You can read more about this here
While surveyTypes[0]
does indeed return 1
, the reason you cannot use it on its own asn an object key, is purely because the syntax for javascript does not allow it. This syntax choice was made to allow you to write plain keys, that don't conflict with expressions. For example:
const obj = {
hello: 'there'
}
vs
const hello = 5
const obj = {
hello: 'there'
}
Notice how these would be ambiguous without bracket notation.