lonewarrior556
lonewarrior556

Reputation: 4479

Why can't I declare an object from array?

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 }

Upvotes: 0

Views: 47

Answers (2)

dsh
dsh

Reputation: 12214

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

Upvotes: 0

deceze
deceze

Reputation: 522042

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;

Upvotes: 2

Related Questions