6

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.

2

3 Answers 3

17

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

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

Comments

3

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.

Comments

0

Actually it is doable by JSON path

For instance: https://jsonpath.com/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.