1

In PHP I can mess around with variable variables and I'm wondering if I can do the same in JavaScript.

I want to create a new object with a property which's name is based on the value of a variable.

if ( obj.name === 'foo' ) {
    var data = { foo: value };
}
if ( obj.name === 'bar' ) {
    var data = { bar: value };
}

Is there a shorter way of doing this without using eval()? Something like:

var data = { obj.name: value };
Till
  • 1,107
  • 12
  • 28

2 Answers2

4

Try this:

var data = {};
data[obj.name] = value;

You can read some more about js objects Here.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
3

Objects in JavaScript are simply hash maps. You can access members by indexing with their names. For your problem you can use

var data = {};
data[obj.name] = value;

I've used this to implement a dynamic dispatch mechanism for arithmetic operations on different numerical types as described here.

thus spake a.k.
  • 1,607
  • 12
  • 12