Reputation: 5298
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
Reputation: 382394
You seem to want
tabs[panel]
This gives the property with name panel
of tabs
.
Upvotes: 0
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