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

But this is OK

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

browser version: Chrome 37.0.2062.124 m

Why Syntax error ? Dose here introduce a new context ? I don't familiar the ECMA spec.

3 Answers 3

5

According to the ECMA Script 5.1 Specification, Object Literal is defined like this

ObjectLiteral :
        { }
        { PropertyNameAndValueList }
        { PropertyNameAndValueList , }

PropertyNameAndValueList :
        PropertyAssignment
        PropertyNameAndValueList , PropertyAssignment

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

PropertyName :
        IdentifierName
        StringLiteral
        NumericLiteral

PropertySetParameterList :
        Identifier

Since [] is not allowed in any of IdentifierName, StringLiteral and NumericLiteral, JavaScript engine is not able to parse the code. That is why it is giving the Syntax error.

So, to actually create an Object with keys and values from an array, you need to construct the Object first and then assign the properties individually, like this

var newObject = {};
newObject[arr[0]] = arr[1];
Sign up to request clarification or add additional context in comments.

Comments

5

In an object literal, the property names must be an identifier (foo), string literal ("foo"), or number literal (1). a[0] is none of these.

When you are adding a property to an existing object, using square bracket syntax, then you use an expression that can be evaluated to a string (which a[0] does).

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

Comments

1

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 ]

Which means, when you write [Expression] as the key, instead of a StringLiteral, NumberLiteral or IdentifierName. The expression gets evaluated and used as the key instead.

Like this:

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

Note however, that ES6 still isn't supported everywhere. In the case this feature isn't supported, just assign the values after the object has been created (like in your second example).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.