ElsT
ElsT

Reputation: 139

how to use a variable inside a javascript object name

I want to use a variable inside an object name.

the javascript object as follows:

var names = {
"john": "29",
"marry": "19",
"dexter": "21",
"robert": "35"
}

The names.{variable here} is determined by a function which looks for the name and place it into the object name, so i can obtain the value

Normally when I wanted to obtain the value of an object, in this case, for John, i will just use names.john

But the problem is the john part is dynamic and determined by a function which looks like this

function displayage(){
   var username = 'John';
   return names.username;

}

I know the code above wont work since it will look for the object "username" instead of the value inside the variable username.

So how am i suppose to do this? or is it impossible?

Upvotes: 0

Views: 1390

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

use [] notation instead of . to use a variable name

function displayage(){
   var username = 'John';
   return names[username];

}

Upvotes: 4

Related Questions