0

I'm trying to access a property from inside an object. When I access the property by manually entering its path, I can retrieve it, but not when doing it dynamically.

What have I missed below?

var myApp = {
    cache : {},
    init: function() {
        myApp.cache.akey = 'A value'; // Set the cached value
        myApp.get('cache', 'akey'); 
    },
    get: function(from, key ) {
        console.log(myApp.from.key); // undefined
        console.log(myApp.cache.akey); // A value
    }
};

2 Answers 2

1

The arguments 'from' and 'key' are not referenced in your example, instead the properties are literals.

Try

myApp[from][key]
Sign up to request clarification or add additional context in comments.

Comments

0

The dot access is literal, if you wanna access by string contained in a variable use subscript notation:

get: function(from, key ) {
    console.log(myApp[from][key]); // Assume from === "cache" and key === "akey", this accesses myApp.cache.akey

}

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.