5

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.

Linas
  • 4,380
  • 17
  • 69
  • 117
  • possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) – Esailija Jun 26 '12 at 18:48
  • possible duplicate of [javascript object, access variable property name?](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-name) – Bergi Jun 26 '12 at 18:51

2 Answers2

16

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'].

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
2

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337