0

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?

1 Answer 1

4

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

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.