Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I don't understand why can't i access values like this:

object = {
    test:{
        value: "Hello world"
    }
}

variable = "value";

//this gives me "Hello world"
console.log(object.test.value);

//this gives me undefined error
console.log(object.test.variable);

By now i can understand that it can't be done this way, but i still need to give some value to the variable and then use that variable to access object values.

share|improve this question
 
possible duplicate of Dynamic object property name –  Esailija Jun 26 '12 at 18:48
 
possible duplicate of javascript object, access variable property name? –  Bergi Jun 26 '12 at 18:51
add comment

2 Answers

up vote 3 down vote accepted

Do it this way:

console.log(object.test[variable]);

Doing it with dots is using literal attribute names. I.e., object.test.value equates to object.test['value'].

share|improve this answer
add comment

You need to do

object.test[variable]

Objects can be accessed using both . and [].

object.test.variable is looking for the literal property "variable", which doesn't exist.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.