Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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'});
share|improve this question

marked as duplicate by Bergi, Jeff Gohlke, djf, Steve Greatrex, Lance Roberts Jul 2 '13 at 18:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 4 down vote accepted

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);
share|improve this answer
    
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 6 '12 at 2:45
    
Ew, go away with that ev[ia]l stuff :P –  ThiefMaster Sep 6 '12 at 10:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.