Chris Burk
Chris Burk

Reputation: 13

How do I use a function result to call a variable name?

I have a <select> with available jobs divided by city, seen here:

<select id="jobs">
    <option value="columbus">Columbus, OH: Material Handler</option>
    <option value="columbus">Columbus, OH: Fulfillment Center Worker</option>
    <option value="baltimore">Baltimore, MD: Material Handler</option>
  </select>

and I am pulling the value as such:

var jobName = document.getElementById("jobs").value;

which returns the result just fine. For the first option I get:

columbus

which is great, now my question is, how do I use this to call another variable, for instance:

var columbus = ['Columbus','3500 Southwest Blvd',', 8 am to 3:30 pm'],
    baltimore = ['Baltimore','913 Old Philadelphia Rd',', 8 am to 3 pm'],
    currentCity = columbus[0] 
console.log(currentCity);

console would return:

Columbus

but, how do I use the jobName to update the currentCity dynamically like:

currentCity = jobName[0]

Upvotes: 1

Views: 59

Answers (2)

voithos
voithos

Reputation: 70552

You seem to want to "look up" a value based on a key. Often, this is done using what's known as a "dictionary" - or, more formally, an "associate array" (sometimes also referred to as a "hash table" - although a hash table is just a one type of dictionary).

JavaScript has something similar that you can use called objects. They are written using curly braces {}, and the keys are separated from values by a colon :. Keys are strings, but the quotes are usually optional. Values can be anything you want.

var cities = {
    columbus: ['Columbus','3500 Southwest Blvd',', 8 am to 3:30 pm'],
    baltimore: ['Baltimore','913 Old Philadelphia Rd',', 8 am to 3 pm']
};

Once you have your key (jobName in your example), you can simply use the cities object to look up whatever you need.

var jobInfo = cities[jobName],
    currentCity = jobInfo[0];

console.log(currentCity);

Side note: JavaScript objects aren't really fully-fledged dictionaries. In most other language, dictionaries can actually use many different types of values for the key (for example, integers), but in JavaScript the key can generally only be a string.

Upvotes: 2

Ismail Badawi
Ismail Badawi

Reputation: 37177

Rather than having different variables, you should use an object to hold all the city information, like this:

var cities = {
  colombus: ['Columbus','3500 Southwest Blvd',', 8 am to 3:30 pm'],
  baltimore: ['Baltimore','913 Old Philadelphia Rd',', 8 am to 3 pm']
};

Then you could write

var currentCity = cities[jobName][0];

Upvotes: 2

Related Questions