o = {a[0]:a[1]} SyntaxError: Unexpected token [ ...">

Javascript how to initialize array using object

> a = ["key","value"]
["key", "value"]
> o = {a[0]:a[1]}
SyntaxError: Unexpected token [

      

But it normal

> o = {}
Object {}
> o[a[0]] = a[1];
"value"
> o
Object {key: "value"}

      

browser version: Chrome 37.0.2062.124 m

Why Syntax error? Does dose introduce new context here? I am not familiar with the ECMA specification.

+3


source to share


3 answers


According to the ECMA Script 5.1 Specification , Object Literal is defined as follows

ObjectLiteral :
        { }
        { PropertyNameAndValueList }
        { PropertyNameAndValueList , }

PropertyNameAndValueList :
        PropertyAssignment
        PropertyNameAndValueList , PropertyAssignment

PropertyAssignment :
        PropertyName : AssignmentExpression
        get PropertyName ( ) { FunctionBody }
        set PropertyName ( PropertySetParameterList ) { FunctionBody }

PropertyName :
        IdentifierName
        StringLiteral
        NumericLiteral

PropertySetParameterList :
        Identifier

      

Since it is []

not allowed in any of the IdentifierName

, StringLiteral

and NumericLiteral

, the JavaScript engine cannot parse the code. This is why it gives a syntax error.



So, to actually create an object with keys and values ​​from an array, you need to first construct the object and then assign the properties individually, for example

var newObject = {};
newObject[arr[0]] = arr[1];

      

+5


source


In object literature, property names must be identifier ( foo

), string literal ( "foo"

), or number literal ( 1

). a[0]

- none of this.

When you add a property to an existing object using the square bracket syntax, you are using an expression that can be evaluated for a string (which does a[0]

).



If you want to use an expression to set a property name, then you must first build an object and then add the property to another expression.

+5


source


In ES6, you have "computed property names" (see http://www.ecma-international.org/ecma-262/6.0/ ):

PropertyName : See 12.2.6
    LiteralPropertyName
    ComputedPropertyName
LiteralPropertyName : See 12.2.6
    IdentifierName
    StringLiteral
    NumericLiteral
ComputedPropertyName : See 12.2.6
    [ AssignmentExpression ]

      

This means that when written [Expression]

as a key, instead of StringLiteral

, NumberLiteral

or IdentifierName

. The expression is evaluated and used in place of the key.

Like this:

> a=["key", "value"]
["key", "value"]
> o={[a[0]]: a[1], [3*3]: "hello"}
Object {key: "value", 9: "hello"}

      

Please note that ES6 is still not supported everywhere. In case this feature is not supported, just assign values ​​after object creation (like in your second example).

+1


source







All Articles