Milano Slesarik Milano Slesarik - 15 days ago 6
Javascript Question

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?

Answer

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>

Comments