Parsing a JSON object of arrays gives different results in IE9

Intro I am working on creating a HighCharts graph from a DataTable table. What I do is iterate over the the rows and columns of the table, convert the strings (we use different thousand separators from the US) to numbers and save them into an object called item. the object has two values item["name"] which is the name of the series and item["data"] which is the data for the series. I then use the .push method to add these objects to an array to send to a Highcharts options object to create the plot. In the case below, I only have three series, but the problem always occurs. The LineOptions is an options-object for the HighCharts Graph.

Code

function plotLineOrBar(type){
    var  jsonData = [];

    var xaxis = $('#masters_table table').find('thead th:not(:first-child)').map(function(){
        return $(this).html();
    }).get();

    $('#masters_table table tbody tr').each(function(){
        item = {};
        item["name"] = $(this).find('td:first-child').html();
        item["data"] = $(this).find('td:not(:first-child)').map(function(){
            return parseInt($(this).html().replace(/\./g, "").replace('',0),10);
        }).get();
        jsonData.push(item);
    });

    console.log(jsonData[0]["name"]); // send the 0th name to console
    console.log(jsonData[1]["name"]); // send the 1st name to console
    console.log(jsonData[2]["name"]); // send the 2nd name to console

    LineOptions.series = (jsonData);
    LineOptions.xAxis.categories = xaxis;
    LineOptions.chart.type=type;
    var chart = new Highcharts.Chart(LineOptions);
}

Problem (The name of the series should be 2320,2321,2336)

In Chrome, the resulting console.log is:

2320
2321
2336

and the corresponding data to each series prints out correctly and everything works flawlessly.

In IE9, the resulting console.log is:

LOG: 2336
LOG: 2336
LOG: 2336

i.e., only the last series gets printed into the array. The result is three series with perfectly overlapping curves, since they have the same data.

I have searched and searched for answers, wrapped by brain around but I can still not figure out what I am doing wrong. I assume though, that my error is a simple one (I hope).

Upvotes: 1

Views: 87

Answers (1)

Jack
Jack

Reputation: 1769

As previously wrote in the comment (for future reference), just define the item variable inside of the loop function, instead of using a "global" one (var item = {} instead of item = {}). This is because in IE9 it seems to be passed by reference, and thus you're pushing the very same object, updated three times (changing its values from iteration to iteration).

P.S. by the way it seems that the other browser you're using, it is creating a new variable every time you use .push and I'm not sure that's the "standard" behavior. One point to IE9!

Upvotes: 3

Related Questions