120

Possible Duplicate:
javascript object, access variable property name?

Trying to get more advanced in my JS...

I have a custom object:

Object myObject = new Object();

myObject.thing = anythingHere;

I would like to be able to retrieve a custom objects property by passing in a string... eg:

var propertyString = 'thing';
alert(myObject.propertyString);

I can't quite figure that out. I've looked at a number of tutorials for custom objects - but nothing shows how to get properties that I don't know the names of... Also - I would like to avoid looping through all properties if possible...

Thanks!!!

Community
  • 1
  • 1
Jay-Nicolas Hackleman
  • 1,355
  • 2
  • 9
  • 7

2 Answers2

222

Simply use myObject['thing'].

ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • 1
    why myObject.thing does not retrive the value? – D.B Sep 19 '16 at 02:51
  • 2
    Because in this comment "thing" is a string (its surrounded by quotes). – Rob Oct 19 '16 at 08:11
  • 1
    if you want something to work for nested objects and you can use lodash something like _.map([object], _.property(propertyPath))[0]; would work. – bobwah Mar 23 '17 at 10:24
  • @D.B the reason myObject.thing doesn't work is because _thing_ is assumed to be a property on myObject when using 'dot' syntax. To get Javascript to treat _thing_ as a variable, you must use [] syntax. – ricanontherun Apr 17 '17 at 15:00
92

You could use:

myObject[propertyString] ;
Ryan
  • 26,884
  • 9
  • 56
  • 83