0

a simple example, Why does this give an error?

var zipped = [[0,1,2]]; var extracted = {}; var i = 0; extracted[zipped[i][0]] = { zipped[i][1]: zipped[i][2] } >>>Uncaught SyntaxError: Unexpected token [(…) 

when this is perfectly fine?

 extracted[0] = { 1: 2 } 
2
  • 2
    You cannot use expression as a key when initializing object property: { zipped[i][1]: .. Commented Sep 11, 2015 at 19:13
  • Also extracted[zipped[i][0]] = { 1 : zipped[i][2] } works, really curious Commented Sep 11, 2015 at 19:17

2 Answers 2

2

Because Javascript object literal syntax does not allow expressions in key parts. Keys are always literal. That's why you can write this:

{ foo: 'bar' } 

And foo is not taken as a variable.

For variable keys, you always have to use this pattern:

var obj = {}; obj[varKey] = value; 
Sign up to request clarification or add additional context in comments.

Comments

0

That is invalid syntax. A number is syntactically allowed in an object literal. Arbitrary expressions are not.

Instead, you need to create the object, then set the attribute.

var obj = extracted[zipped[i][0]] = {}; obj[ zipped[i][1] ] = zipped[i][2]; 

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.