Reputation: 23
In the Chrome dev console, if I do this:
obj1 = Object({"a":"b"})
I can do this:
obj1.a
// -> "b"
But I can't do this:
Object({obj1.a:"c"})
// -> throws "Uncaught SyntaxError: Unexpected token ."
Why?
Upvotes: 2
Views: 40
Reputation: 2405
Because thats awkward syntax. Obj1.c inside your last line wony be evaluated as a variable. It only accepts property names. Obj1.c is not a valid name for a property
Upvotes: 0
Reputation: 13179
Syntax error is because the object key cannot be directly evaluated in that notation. You'd have to do something like this:
obj2 = {};
obj2[obj1.a] = 'c';
obj2[obj1.a];
For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
What is going on at a deeper level is the { }
syntax is using an object initializer to construct the object. The property name of the syntax requires a name, a number, or a string literal
. Evaluation of another object does not meet this requirement.
Upvotes: 3