0

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

2
  • you can't it is an Array of object. no key-value pairs. Commented Sep 10, 2014 at 15:58
  • Can you change the array (that you mistakenly call JSON) to an object with the names as keys? Commented Sep 10, 2014 at 15:59

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

I'm having difficulties with both methods on Safari. Would you happen to know a solution to that?
I just tried it in Safari (7.0.6), and it seems to work for me. What kind of problem to you experience?
3

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;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.