Getting JSON Key from Value or Inverting JSON Data

前端 未结 2 869
长发绾君心
长发绾君心 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:46

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

提交回复
热议问题