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'});
You cannot use the object literal syntax for this purpose. However, you can create a new object and then use the
[]syntax – remember,obj.xyzis equivalent toobj['xyz']– but as you can see with the quotes in the latter, you can use an expression there – such as a variable: