3

I am running this code but it is giving the strange results?

let surveyTypes = [1,2];

let surveyDuration = {
  surveyTypes[0]:  'first',surveyTypes[1]:  'second' 
}

Expected Output:

surveyDuration={1:'first',2:'second'}

Actual Output:

Uncaught SyntaxError: Unexpected token [

ADyson
  • 57,178
  • 14
  • 51
  • 63
Ishmal Ijaz
  • 5,317
  • 3
  • 11
  • 17
  • You may want to use a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead. The keys of the map would be type save and ordered (object literal is not). – HMR Oct 10 '18 at 12:51

2 Answers2

7

You have to wrap the array's item into brackets because you're creating dynamic keys.

let surveyTypes = [1,2];

let surveyDuration = {
  [surveyTypes[0]]:  'first',[surveyTypes[1]]:  'second' 
}

console.log(surveyDuration);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

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.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • please search before posting duplicate answers for a widely known issue. – Ruan Mendes Oct 10 '18 at 12:50
  • the problem was that. I did not found any keyword related with this problem. When i search the error name. I shows me the different stack overflow question. Therefore i posted this question. – Ishmal Ijaz Oct 10 '18 at 12:51
  • 2
    @Sunny My comment was not meant for you, it was for MattWay; with high rep, he should know better that this question has already been answered. In any case, the right name to search for is "computed property name in object initializers" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – Ruan Mendes Oct 10 '18 at 12:55
  • 1
    @JuanMendes I read this question more of a 'why', than a 'how', and thought it deserved its own answer, I just hadn't completed it before it was marked as duplicate. Neither of the marked duplicates explain why in any of their answers. – Matt Way Oct 10 '18 at 13:08
  • @MattWay I guess what you explained was kind of obvious to me. – Ruan Mendes Oct 17 '18 at 10:59