0

I'm having a trouble with getting access to an object's property.

Isn't it possible to get access to an object's property like this?

key["heading"]

key in the code above is a variable.

This code below is the code I'm working on right now.

alertHeading.on('blur', function(){

    var inputtedVal = $(this).val();
    var key = alertMode.val();

    chrome.runtime.getBackgroundPage(function(backgroundPage) {

        var background = backgroundPage.background;

        //(1)This works fine.
        background.setStorage(key, {heading:inputtedVal});  
        console.log(background.getStorage(key));// Object {heading: "aaa"}

        //(2)This doesn't work.
        var alertObject = background.getStorage(key["heading"]);
        console.log(alertObject);// null. I'm expecting to get "aaa".

    });

})

I think I'm making a very simple mistake which comes from my lack of javascript knowledge.

Please help me out to solve this problem.

2
  • what does console.log(alertMode) output? Commented Sep 14, 2013 at 2:41
  • it outputs like this. [input#alert-mode.switch, context: document, selector: "#alert-mode", jquery: "1.10.2", constructor: function, init: function…] Commented Sep 14, 2013 at 2:43

1 Answer 1

4

Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:

var alertObject = background.getStorage(key)["heading"]; // note () and [] placement

// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];

EDIT:

"I haven't understood why it's not an object but a string yet"

Your key variable is set to the return from jQuery's .val() method:

var key = alertMode.val();

...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

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

2 Comments

Thanks!! it does work! I haven't understood why it's not an object but a string yet. But, I'll try to figure it out. I'm going to accept your answer but I need to wait for 7 more minutes until stack overflow let me do it.
Thank you for your edition. It helped me understand the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.