Jonah Katz
Jonah Katz

Reputation: 5298

Cant access object via variable?

I have a javascript object defined as follows:

var tabs = {
    'nav_tweet_search':'tweet-panel',
    'nav_shopping_cart':'cart-panel',
    'nav_stats':'stats-panel'
};

Im trying to access some values using a variable in another function. However, i am getting undefined. I created some console logs ..

console.log("panel: "+panel);
console.log("tabs: "+tabs);
console.log("tabs.panel: "+tabs.panel);

Which outputs,

panel: nav_tweet_search 
tabs: [object Object] 
tabs.panel: undefined

Any reason why i wouldnt be able to access the obj using a variable? If i do "tabs.nav_tweet_search" it works

Upvotes: 0

Views: 55

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382394

You seem to want

tabs[panel]

This gives the property with name panel of tabs.

Upvotes: 0

Matt Zeunert
Matt Zeunert

Reputation: 16571

Use this:

console.log("tabs[panel]: " + tabs[panel]);

When you do tabs.panel the browser will look for a property called "panel", but only "nav_tweet_search", "nav_shopping_cart" and "nav_stats" are defined.

When using brackets the value of the variable will be used as the key for fetching the object property. If you use tabs.panel that's equivalent to tabs["panel"].

Upvotes: 4

Related Questions