简体   繁体   中英

How do I extract JSON string using a JavaScript variable?

I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.

The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name . How can I use the variable name to retrieve the dial_code that it relates to?

JSON

var dialCodes = [
  {"name":"China","dial_code":"+86","code":"CN"},
  {"name":"Afghanistan","dial_code":"+93","code":"AF"}
];

The following code runs on mouse hover of a country

var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() +  ')<br>' + dialCodes[0][countryName].dial_code);

This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair

If you have to support old browsers: Loop over the entries in the array and compare to the given name:

var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
    if(dialCodes[i].name === countryName) {
        dialCode = dialCodes[i].dial_code;
        break;
    }
}
label.html(countryName + ' (' + dialCode + ')');

If you browser support Array.prototype.filter :

dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code

If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code ( CN or AF ) you could avoid looping if you did this:

var dialCodes = {
    CN: { "name":"China","dial_code":"+86","code":"CN" },
    AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}    
};

var code = dialCodes.CN.dial_code;

Or

var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;

Since it's an array you can use filter to extract the data you need.

function getData(type, val) {
  return dialCodes.filter(function (el) {
    return el[type] === val;
  })[0];
}

getData('code', 'CN').dial_code; // +86

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM