从值获取JSON密钥或反转JSON数据 [英] Getting JSON Key from Value or Inverting JSON Data

查看:366
本文介绍了从值获取JSON密钥或反转JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从以下JSON中进行向后选择。我想提取特定状态的缩写。在这种情况下,缩写是键,我开始的值是值。

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?

另一种选择是在处理过程中尽早反转这些数据用交换的键/值给自己一组类似的值。我也有兴趣看到有效的方法。

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'};


推荐答案

没有自动方式来执行此操作。你唯一的选择是遍历列表,直到找到与键匹配的值。

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.

但是,如果你需要多次这样做,你应该有代码使用交换的键/值重建JSON对象,以便将来的查找更快。一个简单的方法:

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

这篇关于从值获取JSON密钥或反转JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆