0

If I have an object, with properties like name, phone_number, etc...how can I access those in Javascript with a variable?

I want to access the property name in javascript by doing something like this:

object {name : "bob", phone_number : "911" }
propertiesArray = ["name","phone_number"];

 object.propertiesArray[0]; // instead of  object.name;
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Apollo
  • 8,384
  • 30
  • 97
  • 186
  • 1
    possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) and [javascript object, access variable property name?](http://stackoverflow.com/q/4255472/218196) and possibly more... – Felix Kling Jun 27 '12 at 15:41
  • Btw, this is not JSON, this is an object literal. – Felix Kling Jun 27 '12 at 15:42

3 Answers3

2
object[propertiesArray[0]]

This will do the trick. Object attributes can be accessed like array indexes using []

jackwanders
  • 14,810
  • 3
  • 39
  • 40
0

You can just use object[propertiesArray[0]].

djc
  • 11,305
  • 5
  • 41
  • 50
0

Try

object[propertiesArray[0]];
Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
mkvcvc
  • 1,495
  • 1
  • 18
  • 40