Javascript - Trouble using for...in to iterate through an object
Asked Answered
C

1

3

I have a dynamically-generated object that looks like this:

colorArray = { 
    AR: "#8BBDE1", 
    AU: "#135D9E", 
    AT: "#8BBDE1",
    ... }

I'm trying to use it to color a map by using this plugin and the 'colors' attribute during the call to the plugin. Like this:

$('#iniDensityMap').vectorMap({
    backgroundColor: '#c2e2f2',
    colors: colorArray,
    ... (some other params)
});

But it doesn't color in the countries. When I hard code this in, it works fine - but it must be dynamically generated for this project, so something like this won't work for me (although it does in fact color the map):

$('#iniDensityMap').vectorMap({
    backgroundColor: '#c2e2f2',
    colors: { AR: "#8BBDE1", AU: "#135D9E", AT: "#8BBDE1" },
    ... (some other params)
});

I've traced the issue far enough into the plugin to find it has something to do with this loop:

setColors: function(key, color) {
  if (typeof key == 'string') {
    this.countries[key].setFill(color);
  } else {

    var colors = key; //This is the parameter passed through to the plugin

    for (var code in colors) {

      //THIS WILL NOT GET CALLED

      if (this.countries[code]) {
        this.countries[code].setFill(colors[code]);
      }
    }
  }
},

I've also tried iterating through the colorArray object on my own, outside of the plugin and I'm running into the same issue. Whatever sits inside the for ( var x in obj ) isn't firing. I've also noticed that colorArray.length returns undefined. Another important note is that I've instantiated var colorArray = {}; in a separate call, attempting to ensure that it is sitting at the global scope and able to be manipulated.

I'm thinking that the problem is either:

  1. The way I'm dynamically populating the object - colorArray[cCode] = cColor; (in a jQuery .each call)
  2. I'm once again confusing the differences between Arrays() and Objects() in javascript
  3. It is a scope issue perhaps?
  4. Some combination of everything above.

EDIT #1: I've moved my additional question about Objects in the Console in Firebug to a new post HERE. That question deals more specifically with Firebug than the underlying JS problem I'm asking about here.

Edit #2: Additional info Here's the code I'm using to dynamically populate the Object:

function parseDensityMapXML() {
$.ajax({
    type: "GET",
    url: "media/XML/mapCountryData.xml",
    dataType: "xml",
    success: function (xml) {
        $(xml).find("Country").each(function () {
            var cName = $(this).find("Name").text();
            var cIniCount = $(this).find("InitiativeCount").text();
            var cUrl = $(this).find("SearchURL").text();
            var cCode = $(this).find("CountryCode").text();

            //Populate the JS Object
            iniDensityData[cCode] = { "initiatives": cIniCount, "url": cUrl, "name": cName };
            //set colors according to values of initiatives count
            colorArray[cCode] = getCountryColor(cIniCount);
        });
    }
});
} //end function parseDensityMapXML();

This function is then called on a click event of a checkbox elsewhere on the page. The Objects iniDensityData and colorArray are declared in the head of the html file - hoping that keeps them in global scope:

<script type="text/javascript">
    //Initialize a bunch of variables in the global scope
    iniDensityData = {};
    colorArray = {};
</script>

And finally, here's a snippet from the XML file that is being read:

<?xml version="1.0" encoding="utf-8"?>
<icapCountryData>
  <Country>
    <Name>Albania</Name>
    <CountryCode>AL</CountryCode>
    <InitiativeCount>7</InitiativeCount>
    <SearchURL>~/advance_search.aspx?search=6</SearchURL>
  </Country>
  <Country>
    <Name>Argentina</Name>
    <CountryCode>AR</CountryCode>
    <InitiativeCount>15</InitiativeCount>
    <SearchURL>~/advance_search.aspx?search=11</SearchURL>
  </Country>
  ... and so on ...
</icapCountryData>
Confess answered 31/7, 2012 at 22:48 Comment(8)
you are definitely confusing [] and {}, at least. {} doesn't have a length property unless you explicitly add one.Epochmaking
also: when you set a breakpoint on your for loop, is the value of colors what you expect it to be?Epochmaking
Just taking a shot in the dark, here...you mention that you're using the jQuery.each function. Are you by chance using the this keyword inside of that function? e.g. this.countries? this being improperly bound is one of the most common causes of errors in JavaScript.Anneal
@DanDaviesBrackett yeah, I'm pretty sure I want to use {} (Object, correct?) and that .length won't work for that - but certainly the for/in loop should?Confess
@HerroRygar Pretty sure that's done correctly, in the success callback of a jQuery ajax call, I'm doing this: $(xml).find("Country").each(function () { var cCode = $(this).find("CountryCode").text(); ...some more stuff } and then populating the colorArray like this: colorArray[cCode] = cColor;Confess
What about the colorArray variable (in truth, it's actually an object though)? What about the scope of that? It would help quite a bit if you would post more code to get the full context. Using developer tools may also help you dig deeper; place the following statement right before calling the vectorMap function: console.log(colorArray);. This will write out to your browser's debug console the contents of the colorArray object. Google instructions on how to pull up the console. My guess is that this object is going to be either {},null, or undefined.Anneal
...but yeah, if you could post the entire code block in question, that would make it much easier to diagnose a scope issue.Anneal
You might consider not calling an Object an Array. An array in javascript uses square brackets var arr = [];. Calling it an array makes us think you're confused...Stylize
C
3

Solved it! Originally, I was calling the function parseDensityMapXML() and then immediately after it calling another function loadDensityMapXML() which took the object created dynamically in the first function and iterated through it. Problem was, it wasn't called as a callback from the first function, so was firing before the Object had even been built.

To fix, I just amended the first function mentioned above to call the second function after the .each() was finished creating the objects:

function parseDensityMapXML() {
$.ajax({
    type: "GET",
    url: "media/XML/mapCountryData.xml",
    dataType: "xml",
    success: function (xml) {
        $(xml).find("Country").each(function () {
            var cName = $(this).find("Name").text();
            var cIniCount = $(this).find("InitiativeCount").text();
            var cUrl = $(this).find("SearchURL").text();
            var cCode = $(this).find("CountryCode").text();

            //Populate the JS Object
            iniDensityData[cCode] = { "initiatives": cIniCount, "url": cUrl, "name": cName };
            //set colors according to values of initiatives count
            colorArray[cCode] = getCountryColor(cIniCount);
        });

        /* and then call the jVectorMap plugin - this MUST be done as a callback
           after the above parsing.  If called separately, it will fire before the
           objects iniDensityData and colorArray are created! */
        loadDensityMapXML();
    }
});
} //end function parseDensityMapXML();
Confess answered 1/8, 2012 at 18:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.