red
red

Reputation: 2050

Accessing Object information in Javascript with a variable?

I don't seem to understand how to access an objects value properly.

My object:

  // countrycode: "Radio station name"
  var radioStations = {
    fi: "Foo",
    hu: "Bar",
    am: "Baz"
  };

Then I have a variable called code which comes from a jQuery plugin, and has the countrycode of the country the user is mouseovering on a vector map.

I'd need to use code to add the radio stations name into the tooltip in here:

onLabelShow: function(event, label, code){
  if ( code in radioStations ) {
    label.text(radioStations.code); // <- doesn't work
  } else  { // hide tooltips for countries we don't operate in
    event.preventDefault();
  }
},

Upvotes: 1

Views: 169

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337713

You need to us array notation to access the object by a variable. Try this:

onLabelShow: function(event, label, code){
    if (code in radioStations) {
        label.text(radioStations[code]);
    } 
    else  { 
        event.preventDefault();
    }
},

Example fiddle

Upvotes: 6

thecodeparadox
thecodeparadox

Reputation: 87073

You can use:

onLabelShow: function(event, label, code){
  if(radioStations[code]) {
   label.text(radioStations[code]);
  } else {
   event.preventDefault();
  }
}

DEMO

Upvotes: 1

Related Questions