Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - Getting JSON Key from Value or Inverting JSON Data

Getting single key from Value

I would like to do a backwards selection from the following JSON. I'd like to extract the abbreviation for a particular state. In this situation, the abbreviation is the key, and the value that I'm starting with is the value.

Certainly I can loop through each value, comparing the value to my value, and select the key when the match is made. Is this the best way to approach something like this? Or is there a better way?

Inverting JSON Data

Another option would to invert this data early in processing to give myself a similar set of values with the keys/values swapped. I would be interested in seeing methods for doing this efficiently as well.

var States = {AL: 'Alabama', AK: 'Alaska', AZ: 'Arizona', AR: 'Arkansas', 
              CA: 'California', CO: 'Colorado', CT: 'Connecticut', 
              DE: 'Delaware', DC: 'District of Columbia', FL: 'Florida', 
              GA: 'Georgia', HI: 'Hawaii', ID: 'Idaho', IL: 'Illinois', 
              IN: 'Indiana', IA: 'Iowa', KS: 'Kansas', KY: 'Kentucky', 
              LA: 'Louisiana', ME: 'Maine', MD: 'Maryland', MA: 'Massachusetts', 
              MI: 'Michigan', MN: 'Minnesota', MO: 'Missouri', MT: 'Montana', 
              NE: 'Nebraska', NV: 'Nevada', NH: 'New Hampshire', 
              NJ: 'New Jersey', NM: 'New Mexico', NY: 'New York', 
              NC: 'North Carolina', ND: 'North Dakota', OH: 'Ohio', 
              OK: 'Oklahoma', OR: 'Oregon', PA: 'Pennsylvania', 
              RI: 'Rhode Island', SC: 'South Carolina', 
              SD: 'South Dakota', TN: 'Tennessee', TX: 'Texas', UT: 'Utah', 
              VT: 'Vermont', VA: 'Virginia', WA: 'Washington', 
              WV: 'West Virginia', WI: 'Wisconsin', WY: 'Wyoming'};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...