Apollo
Apollo

Reputation: 9054

Accessing property of object with variable

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;

Upvotes: 0

Views: 352

Answers (3)

mkvcvc
mkvcvc

Reputation: 1565

Try

object[propertiesArray[0]];

Upvotes: 0

djc
djc

Reputation: 11711

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

Upvotes: 0

jackwanders
jackwanders

Reputation: 16020

object[propertiesArray[0]]

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

Upvotes: 2

Related Questions