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
  • 795,719
  • 175
  • 1,089
  • 1,143
Apollo
  • 8,874
  • 32
  • 104
  • 192
  • 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
  • 15,612
  • 3
  • 40
  • 40
0

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

djc
  • 11,603
  • 5
  • 41
  • 54
0

Try

object[propertiesArray[0]];
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
mkvcvc
  • 1,515
  • 1
  • 18
  • 41