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'});
0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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...!
Ew, go away with that ev[ia]l stuff :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.