using country code as array/object names? scoping issue?

551 views Asked by At

could anyone help me with this please, used Canada as example:

var CA = {
    name: "Canada Name",
    iso: "CA",
    percentage: "23.4",
    color: getColor(23.4)
};

$(function() {

    $('#world-map').vectorMap({
        map: 'world_mill_en',
        .
        .
        onRegionTipShow: function(event, wrap, code) {
            wrap.html('hello ' + code); // working, outputs "hello CA"
            console.log(CA.name); // working, outputs "Canada Name"
            console.log(code.name); // not working - undefined
        },
        .
        .

How can I use the "code" to refer to the variable (CA in this case)? As I see code outputs a string but I just can not turn it to a form that works

Thx

1

There are 1 answers

1
Rory McCrossan On BEST ANSWER

You would need to further wrap your CA object in another object, something like this:

var langs = {
    CA: {
        name: "Canada Name", 
        iso: "CA", 
        percentage: "23.4", 
        color: getColor(23.4)
    }
}

You can then access the properties of langs using bracket notation. So assuming code = 'CA' in your example:

onRegionTipShow: function(event, wrap, code){
    wrap.html('hello ' + code);     // = 'hello CA'
    console.log(langs[code].name);  // = 'Canada Name'
},