Search code examples
javascriptjsontrimjvectormap

JvectorMap Trim data output


I'm using JvectorMap to map carriers by state for easy editing the json data looks like this:

 {
"states": {
    "2015": {
        "US-AK": [" Aenta", " Assurant", "     ", "         ", "           ", "     ", "       "],
        "US-AL": [" Aenta", " Assurant", "     ", "         ", " Goden Rule", "     ", " Humana"],
        "US-AR": [" Aenta", " Assurant", "     ", "         ", "           ", "     ", "       "],
        "US-AZ": [" Aenta", "         ", "     ", "         ", " Goden Rule", "     ", " Humana"],
        "US-CA": [" Aenta", " Assurant", "     ", "         ", "           ", "     ", "       "],
          }
        }
    }

The code that renders the map is this:

$(function(){
$.getJSON('../js/medicalOff.json', function(data){
    var val = 2015;
        statesValues = jvm.values.apply({}, jvm.values(data.states));
  $('#map').vectorMap({
        map: 'us_merc_en',
        backgroundColor: '#ffffff',
        regionStyle: {
            initial:{
         fill: '#87c9b4',   
        },
            hover:{
             fill:'#2e8f70',   
            },
        },
onRegionTipShow: function(e, label, code) {
var str =  data.states[val][code];
var trim = str.replace(/(^,)|(,$)/g, "");
 label.html('<b>' + label.html() + '</b>' + '<br> ' + trim);
},
  });
});
});

Before I added var str = data.states[val][code]; var trim = str.replace(/(^,)|(,$)/g, ""); the data came out like Texas: ,,,Assurant,,,Humana. Now I'm not very good at JavaScript but I have a basic understanding of it. Currently I get "Undefined is not a function" error. What would be the correct way to implement this part

var str =  data.states[val][code];
var trim = str.replace(/(^,)|(,$)/g, "");

Solution

  • I'm assuming the line that has the error is var trim = str.replace(/(^,)|(,$)/g, "");. If I am assuming correctly then that means str is not a string, but rather some other object.

    In a case like this, you need to inspect "If it's not a string, what is str?"

    One way to inspect is to alert(str) and see what pops up. Place the alert line directly before the line that has the error.

    Of course alert(str) is the same as alert(data.states[val][code]). You may find help by using alert(JSON.stringify(data.states[val][code])) or alert(JSON.stringify(data.states[val])).