Ashfame
Ashfame

Reputation: 1769

Access JS object with a key

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.

Upvotes: 0

Views: 448

Answers (2)

MK_Dev
MK_Dev

Reputation: 3343

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

Upvotes: 1

Rudie
Rudie

Reputation: 53890

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.

Upvotes: 0

Related Questions