0

I have a javascript object like this

var obj={
    a:{x: "someValue", y:"anotherValue"},
    b:{x: "bValue", y:"anotherbValue"}
};

and I am trying to reference it like this

function(some_value){
    alert("some_value is " + some_value + " with type " + typeof some_value);
    // prints  some_value is a  with type  string 
    var t;
    t=obj[some_value]["x"];   // doesn't work   
    some_value="a";
    t=obj[some_value]["x"];  // this does work
    t=obj["a"]["x"];     // and so does this
}

I would really like understand what is going on here . Ideally I'd like to reference my object with the value passed to the function. Thanks

4
  • sorry there is a typo - there is not two double quotes on the last object in the real code Commented Apr 29, 2012 at 1:43
  • 3
    You can edit your question. stackoverflow.com/posts/10369028/edit Commented Apr 29, 2012 at 1:44
  • 1
    If some_value is indeed "a", then t=obj[some_value]["x"]; will work. Commented Apr 29, 2012 at 1:46
  • How are you calling the function? Commented Apr 29, 2012 at 1:49

2 Answers 2

1

I can only assume that your variable some_value must not contain the value a. It is possible that it has extra white space characters.

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

2 Comments

+1 Seems like it may be a whitespace issue judging by the output of the alert.
yes that was it- thanks, at least I won't forget to check for that again since I have been fiddling with it for ages.
0

In JS, when a property does not exist, it returns an undefined. in the case of the following code, if the value contained in the variable some_value does not exist as a property in obj, t is undefined

//if some_value is neither a nor b
t = obj[some_value] // t === undefined

if you try to extract a property from an undefined value, the browser reports an error:

//if some_value is neither a nor b
t = obj[some_value]["x"] // error

you can check the existence of a property before you try accessing it by using hasOwnProperty().

if(obj.hasOwnProperty(somevalue)){
    //exists
} else {
    //does not exist
}

you can do a "loose check" but it's not reliable as anything "falsy" will call it "non-existent" even though there is a value.

if(obj[somevalue]){
    //is truthy
} else {
    //obj[somevalue] either:
    //does not exist
    //an empty string
    //a boolean false
    //null
    //anything "falsy"
}

1 Comment

thanks, I used your suggestion hasOwnProperty and found that it was returning false, some_value="my_lookup_value " Whitespace! Ahggg

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.