-1

I have a json file that I am trying to access using the following jquery function.

$.ajax({
    type: 'GET',
    url: '/data/coffee.json',
    dataType:'json',
    success: function(data) {
        let widget = show(data);
        $("#Meals").html(widget);
    }
});

function show(data) {
    let statusHtml = '<ul>';
    $.each(data.prices, function(i, meal){
        statusHtml += '<li> name: '+ meal.item + '</li>';
        statusHtml += '<li> price: '+ meal.price + '</li>';
    });
    statusHtml += '</ul>';
    return statusHtml;
}

The data I am trying to access is as follows:

[
  {
    "shopName": "The Coffee Connection",
    "address": "123 Lakeside Way",
    "phone": "16503600708",
    "prices": [
  {
   "item": "Cafe Latte",
   "price": 4.75
  },
  {
   "item": "Flat White",
   "price": 4.75
  },
  {
   "item": "Cappucino",
   "price": 3.85
  },
  {
   "item": "Single Espresso",
   "price": 2.05
  },
  {
   "item": "Double Espresso",
   "price": 3.75
  },
  {
   "item": "Americano",
   "price": 3.75
  }
  ]
 }
]

I have tried to console.log('success', data); and this returns the prices array in the console. But for some reason it is not showing up when I run this code. Any help would be appreciated.

instead
  • 3,101
  • 2
  • 26
  • 35
AltBrian
  • 2,392
  • 9
  • 29
  • 58

2 Answers2

2

data.prices isn't valid. data is an array, so you need data[0].prices, and etc. loop through data first, and that variable would have a prices property. or just use

function show(data) {
    let statusHtml = '<ul>';
    $.each(data[0].prices, function(i, meal){
        statusHtml += '<li> name: '+ meal.item + '</li>';
        statusHtml += '<li> price: '+ meal.price + '</li>';
    });
    statusHtml += '</ul>';
    return statusHtml;
}
Trevor
  • 2,792
  • 1
  • 30
  • 43
2

Data is an Array, this should work:

$.each(data[0].prices, function(i, meal){
    statusHtml += '<li> name: '+ meal.item + '</li>';
    statusHtml += '<li> price: '+ meal.price + '</li>';
});
agustin37
  • 121
  • 6