0
\$\begingroup\$

I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

if (inputFive == "Corporation"){
inputFive = "534"
}else if (inputFive == "LLC"){
inputFive = "535"
}else if(inputFive == "LLP"){
inputFive = "536"
}else if(inputFive == "Partnership"){
inputFive = "537"
}else if(inputFive == "Sole Proprietorship"){
inputFive = "538"
}else if(inputFive == "Limited Partnership"){
inputFive = "539"
} else {
inputFive = "540"
}

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. All options/hints will be appreciated!

\$\endgroup\$
2
  • \$\begingroup\$ This looks like a good example where key/value pairs would come in handy. You could refractor your code to use a dictionary \$\endgroup\$
    – Ludisposed
    Jul 7, 2017 at 17:18
  • \$\begingroup\$ @Ludisposed Thank you for your response! Could you please expand on what you mean a little bit more? (maybe what resource to look at and what now). Thanks again. \$\endgroup\$
    – KV Ghumaan
    Jul 7, 2017 at 17:21

1 Answer 1

1
\$\begingroup\$

I am not a Javascript programmer, so I will try my best how to explain to use a dictionary. A dictionary means you can add a value to a key

Example from dotnet perls

# Creations of a dictionary
var dictionary = {"Corporation":534,"LLC":535,"LLP":536,"Partnership":537,"Sole Proprietorship":538,"Limited Partnership":539};

# Getting values of dictionary
new_inputFive = dictionary[inputfive]

# For instance when inputfive="LLC" new_inputFive = 535
\$\endgroup\$
4
  • \$\begingroup\$ Hello and thanks again! I am using JavaScript, not Java. Is this possible in JS? \$\endgroup\$
    – KV Ghumaan
    Jul 7, 2017 at 17:28
  • \$\begingroup\$ Sorry my bad. Will edit \$\endgroup\$
    – Ludisposed
    Jul 7, 2017 at 17:31
  • \$\begingroup\$ I forgot qoutes around the numbers, and will try to give more information. But unable to edit at the moment since I am busy \$\endgroup\$
    – Ludisposed
    Jul 7, 2017 at 18:20
  • \$\begingroup\$ To get the default you could do new_inputFive = dictionary[inputfive] || '540' \$\endgroup\$ Jul 7, 2017 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.