Milano
Milano

Reputation: 18725

JS/JQuery: Can't access array elements in json

I'm working on a charts on my page. Since I work with Django, I have to pass JSON of data into the HTML and then parse the JSON to get the data.

The problem is that console says:

Uncaught TypeError: Cannot read property '0' of undefined(…)

function drawChart() {
    var google_chart_json = {"MyKey": [[[2016, 11, 2], 156.0], [[2016, 11, 3], 69.0], [[2016, 11, 4], 126.0], [[2016, 11, 5], 67.0], [[2016, 11, 6], 97.0], [[2016, 11, 7], 193.0], [[2016, 11, 8], 96.0], [[2016, 11, 9], 64.0], [[2016, 11, 10], 117.0], [[2016, 11, 11], 190.0]]};

    $.each(google_chart_json, function (key, val) {
        console.log(key); 
        $.each(val,function (scan) {
            var year = scan[0][0]
            console.log(year)
        })
    });
    ....

As you can see var year should be 2016 etc.

Where is the problem?

Upvotes: 0

Views: 63

Answers (2)

chrki
chrki

Reputation: 6323

The issue is that scan in your innermost loop only is the key value (or in this case, the array index, 0-9), not the complete array.

$.each(google_chart_json, function (key, val) {
    console.log(key); 
    $.each(val,function (scan) {
        console.log(google_chart_json[key][scan][0][0])
    })
});

Upvotes: 1

JLRishe
JLRishe

Reputation: 101662

The first parameter passed into the $.each callback is a key or array index. The second parameter is the value. You got this right in your outer $.each, but not the inner one.

Fixed:

function drawChart() {
  var google_chart_json = {
    "MyKey": [
      [[2016, 11, 2], 156.0],
      [[2016, 11, 3], 69.0],
      [[2016, 11, 4], 126.0],
      [[2016, 11, 5], 67.0],
      [[2016, 11, 6], 97.0],
      [[2016, 11, 7], 193.0],
      [[2016, 11, 8], 96.0],
      [[2016, 11, 9], 64.0],
      [[2016, 11, 10], 117.0],
      [[2016, 11, 11], 190.0]
    ]
  };

  $.each(google_chart_json, function(key, val) {
    console.log(key);
    $.each(val, function(idx, scan) {
      var year = scan[0][0]
      console.log(year)
    })
  });
}

drawChart();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions