Javascript - Trouble using for…in to iterate through an object

前端 未结 1 843

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

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


        
1条回答
  •  鱼传尺愫
    2021-01-14 10:58

    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();
    

    0 讨论(0)
提交回复
热议问题