Reputation: 4479
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
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
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