Getting JSON Key from Value or Inverting JSON Data

前端 未结 2 881
长发绾君心
长发绾君心 2020-12-10 16:18

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 thi

2条回答
  •  旧巷少年郎
    2020-12-10 16:47

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

提交回复
热议问题