15

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.

tommcdo
  • 277
  • 1
  • 2
  • 7
  • I think you'll have to stick to the array syntax.. maybe eval('person.'+prop+' = "January 12"') will do the trick, but I don't think this is the optimal solution – Philippe Boissonneault Sep 26 '12 at 18:15
  • 1
    @PhilippeBoissonneault -- Ack! Eval is *not* needed... please don't use it in this context. – Jeremy J Starcher Sep 26 '12 at 18:16
  • You're looking for the equivalent of the PHP variable variables: `$foo = bar; $bar = '123'; echo $$foo;// actually displays '123'` – Ray Jan 30 '13 at 19:32
  • possible duplicate of [Using a variable for a Javascript object key](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key) – Bergi Jan 30 '14 at 04:44

4 Answers4

7

No, this will not work, that is why, if you are dynamically setting property names, array like notation is suggested and used.

var k='propertyname';
object[k]="value";

this works while using the dot notation to set index or property name from vatiable is not possible.

geekman
  • 2,224
  • 13
  • 17
6

ES6 now allows for this:

var obj = {
  [prop]: 'value'
};
dwhieb
  • 1,706
  • 19
  • 29
4

For people who need a drop-in replacement for dot syntax where the keys are objects instead of strings (say for nesting inside a parent Object), here are some workarounds:

var developers = {
    person: {
        'name': 'John',
        'age': 23
    },
    anarchist: (function(){ var a = {};
        a['name'] = 'John';
        a['age'] = 23;
        a[false] = false;
        a[1] = 1;
        a[window] = window;
    return a; })(),
    conformist: _.object([
        ['name', 'John'],
        ['age', 23],
        [false, false],
        [1, 1],
        [window, window]
    ])
};

// console.log(developers); // <- to see var dump in Firebug

The anarchist element uses a self-executing-function that gets garbage collected after the call, and the conformist element uses the _.object() function if you can include underscore.js in your site.

I wish that the built-in Object() and Array() functions allowed for passing in keys and values the way underscore.js does it :-)

Zack Morris
  • 4,727
  • 2
  • 55
  • 83
2

You can not do this with objects, but if you consider using a constructor function instead, it could look something like this:

var prop = "birthday";
var Person = function() {
    this.name = "Bob";
    this[prop] = "January 12";
};
var bob = new Person();

Of course you still have the array notation here, but maybe you like this aproach anyway :)

sra
  • 6,338
  • 3
  • 20
  • 17