JavaScript gives you a lot of ways to declare objects. When you have most of the data available at hand, the most convenient (in my opinion) is as follows:
var person = {
name: 'John',
age: 23
}; // "object literal syntax"
A curious thing about this syntax is that it is identical to this:
var person = {
'name': 'John',
'age': 23
}; // "object literal syntax"
That is, you can use quotes or omit them for the property names.
When comparing that to the way setting a single property works, you have two options:
person.birthday = "January 12"; // "dot syntax"
or
person['birthday'] = "January 12"; // "array syntax"
The "dot syntax" only works when the right operand is the actual property name. If you want to use a variable for the property name, you have to use "array syntax", i.e.:
var prop = "birthday";
person[prop] = "January 12";
Now, is it possible to use a variable for the property name in the "object literal syntax"? Since it doesn't matter if you quote the property names, there doesn't seem to be an obvious way to use a variable there. I'm looking for something like this:
var prop = "birthday";
var person = {
name: 'John',
age: 23,
(prop): 'January 12'
};
Here I'm using (prop) as the imaginary syntax used to express that this is a variable and not a literal string.
Thanks.