Tom Tom - 1 month ago 11
JSON Question

Trying to access two arrays in JSON with $.each

I am having a hard time accessing both values in an array. Im not sure what I am doing wrong. basically I just want to output both images and display them on the page. Hope someone can help me with this. Below is my code:



(function() {

'use strict';

var url = 'path to json';

$.getJSON(url, function(json) {

//store json data into variable
var data = (json);

//store data in empty string
var images = '';

//retrieve values from json file
$.each(data, function (i, item) {
images += '<img src="' + item[i].imageURL + '">';
});

//append results to div

$('#images').html(images);

});

})();




Answer

Since there are 2 possible fields which could contain the image path, select the correct one. In addition, use item[0] since the nested array has length=1:

(function() {
  'use strict';

  var url = 'path to json';

  $.getJSON(url, function(json) {

    //store json data into variable 
    var data = (json);

    //store data in empty string
    var images = '';

    //retrieve values from json file
    $.each(data, function(i, item) {
      images += '<img src="' + (item[0].imageURL || item[0].category) + '">';
    });

    //append results to div

    $('#images').html(images);
  });
})();