0

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 in a function (local scope) by the way..

Christoph
  • 50,121
  • 21
  • 99
  • 128
BrownChiLD
  • 3,545
  • 9
  • 43
  • 61

2 Answers2

2

You can access Object properties in two ways:

o.propertyname
//or
o.["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]
Christoph
  • 50,121
  • 21
  • 99
  • 128
1

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • sorry, but its still wrong - it should be `objectName['propertyName']` ... – Christoph May 07 '13 at 07:30
  • @Christoph I disagree. If propertyName is a variable holding the name of the property, which should be the case if the name is dynamic, then it's the correct syntax. – Denys Séguret May 07 '13 at 07:32
  • With your comment added, the intend is clear. However as it currently stands, your answer implies that `propertyName` is the name of the property and not a variable, so it's very misleading. If you want to make it a community wiki your answer should be rocksolid and not as ambiguous as it currently is. – Christoph May 07 '13 at 07:35