Skip to content Skip to sidebar Skip to footer

How To Access A Dynamic Property: Objectname.{variable}

i need to access objectName.myID but the 'myID' part is dynamically generated.. how do i do this? i tried this['objectName.'+ variable] i'd hate to use eval... ps this happens

Solution 1:

You can access Object properties in two ways:

o.propertyname//oro.["propertyname"]

When using the bracket notation you have to put the propertyname in quotes or else it will be interpreted as a variable name (which in your case is exactly what you want). So in your case where you have stored the name of the property as a string, the way to go would be:

var variable = "propertyname";
o[variable];
/* /\ variable is replace with it's string representation "propertyname" */

You can even call methods this way:

var o = {};
var functionname = 'toString';
o[functionname]();

You can mix both notations, your example would look like:

var obj = 'objectName';
var prop = 'myID';
this[obj][prop]
// or this is possible too:this.objectName[prop]

Solution 2:

Assuming propertyName is the name of a variable holding the name of the property, for example 'myId', then you can use.

objectName[propertyName]

More details in the MDN : Working with objects

Post a Comment for "How To Access A Dynamic Property: Objectname.{variable}"