Home > Software engineering >  Is it possible to have multiple keys for a single value in Javascript?
Is it possible to have multiple keys for a single value in Javascript?

Time:03-22

I'm writing a program that cycles through a dictionary with a list of every state's abbreviation and minimum wage, where the abbreviation is the key and the minimum wage float is the value. However, it occurred to me that many people would not know their state's abbreviation. Is there a way to have multiple keys, so that the user could input either "Delaware" or "DE" and get the same output value? I know I could just create another entry into the dictionary with the same value and the key name of the state, but I'm interested about whether I can manage complexity with this.

Pretty much all I've tried is putting commas on the key value side. I know putting 50 extra keys with the state names is always a possibility, I just wonder if I can manage complexity in a different way.

CodePudding user response:

I do not understand why you have to take input from user, where you could just give a selectbox in the UI. Anyways I am assuming, thats not possible in your case. If you really need to keep all the possible state's abbreviation input in an object (dictionary), you can keep it in an array. Keep in mind that its not an optimal way of handling the situtation.

const obj = {
  abbreviations: ['DE', 'Delware', 'DRE' ],
  minimumWages: 10
}

Then you can find the wages by doing -

const userInput = 'DE'
if(obj.abbreviations.indexOf(userInput)!== -1) {
  return obj.minimumWages;
}

CodePudding user response:

You can do a simple configuration that you transform in dictionary like this

const config = {
 DE : {alias:['Delaware', 'DE'], //every alias
       minimunWage: 10
       }
}

const dictonary = Object.entries(config).reduce((o, [k, v]) => {
  v.alias.forEach(a => {o[a] = v.minimunWage})
  return o
}, {})

console.log(dictonary['DE'])
console.log(dictonary['Delaware'])

  • Related