I would like to do a backwards selection from the following JSON. I\'d like to extract the abbreviation for a particular state. In thi
The only other logical solution would be to have the long name be the key and the abbreviation be the value. Selection is usually made on keys since they are unique, as they should.
You could save yourself from iterating every time you want to get the value, by doing the key - value switch the first time.
function switcharoo(o) {
var t = {};
for (var i in o) {
if(o.hasOwnProperty(i)){
t[o[i]] = i ;
}
}
return t;
}
console.log(switcharoo({AZ: "Arizona"}));
There's no "automatic" way to do this. Your only option is to loop through the list until you find the value that matches the key.
But, if you need to do this multiple times, you should have the code rebuild the JSON object with key/values swapped, so that future lookups are faster. A simple way:
function swapJsonKeyValues(input) {
var one, output = {};
for (one in input) {
if (input.hasOwnProperty(one)) {
output[input[one]] = one;
}
}
return output;
}
var stateAbbrs = swapJsonKeyValues(States);