2

I have an object:

var obj = {fields : []};

And a variable:

var x = "property_name";

Now how do I use the value in the variable x as the property name for the object that I'm going to push inside the array?

I tried something like the one below, but it takes x literally and uses it as the property name. What I want to use is the value stored in the variable x. Is that possible?

obj.fields.push({x : 'im a value'});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wern Ancheta
  • 22,397
  • 38
  • 100
  • 139

1 Answers1

4

You cannot use the object literal syntax for this purpose. However, you can create a new object and then use the [] syntax - remember, obj.xyz is equivalent to obj['xyz'] - but as you can see with the quotes in the latter, you can use an expression there - such as a variable:

var x = "property_name";
var obj = {};
obj[x] = 'value';
obj.fields.push(obj);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • And then there is the one who's name is mentioned at the risk of eternal damnation in agony while loved ones suffer: `var x = 'property_name'; var obj = eval('({' + x + ': "value"})');`. Agggh, the lights are fading...! – RobG Sep 06 '12 at 02:45
  • Ew, go away with that ev[ia]l stuff :P – ThiefMaster Sep 06 '12 at 10:33