0

I can access a value like driver.my_friends["793659690"].name but now I am using it in a loop where key will hold the key.

driver.my_friends[key].name doesn't work. Says undefined, and driver.my_friends["key"].name will look for a key named key. So how do I use it so that the variable of the variable is evaluated too.

3
  • 2
    driver.my_friends[key].name should work, so most likely whatever key you're iterating through doesn't exist. Try debugging other data yourself or providing more of the surrounding code. Commented May 16, 2011 at 21:42
  • driver.my_friends[key].name is correct. My guess is that key is set to the wrong value. See jsFiddle for a working example. Commented May 16, 2011 at 21:42
  • @mVChr @lonesomeday Thanks! You were right, logic error X( Commented May 16, 2011 at 21:56

2 Answers 2

1

when you're iterating over an object's properties, some "garbage" may get into "key" variable. I would suggest the following:

for (var key in driver.my_friends) {
  if (key && driver.my_friends[key] && driver.my_friends[key].name) {
    // Do what you need here
  }
}

Also, make sure that when the value of driver.my_friends[key] gets set, the key is the same as the one used for reading it

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

Comments

0

driver.my_friends[key].name is the right way. It is possible that no key like key exists in driver.my_friends =) and/or that .name doesn't exist in that object.

You can debug that very easily:

console.log(driver.my_friends[key]);
console.log(driver.my_friends[key].name);

Even IE8 has a console like that.

1 Comment

Thanks! The key didn't existed as in that loop my key was in value and key were very small numbers.

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.