2

I want to extract data from Json array and append it with html table with jquery like

  • idly 5
  • dosa 20

This is how my browser console prints what my server returned

    {hotelMitem: Array(5)}
    hotelMitem: Array(5)
    0: {hname: "idly", iprice: "5"}
    1: {hname: "dosa", iprice: "20"}
    2: {hname: "dosa", iprice: "20"}
    3: {hname: "dosa", iprice: "20"}
    4: {hname: "dosa", iprice: "20"}
    length: 5
    __proto__: Array(0)
    __proto__: Object

But when i try to iterate & print with jQuery

    var _jsonString = "";
                for(var key in data){
                    _jsonString +="key "+key+" value "+data[key]+ '</br>';
                }
    $("#datatable").append(_jsonString)

HTML OUTPUT what i get

key hotelMitem value [object Object],[object Object],[object Object],[object Object],[object Object]

1 Answers1

2

You need to loop through data.hotelMitem, not data itself. As the keys are static you can just access them directly without the additional inner loop. You then need to build the actual HTML to populate the table with tr and td elements. You can achieve that using map(), like this:

var data = {
  hotelMitem: [{
    hname: "idly",
    iprice: "5"
  }, {
    hname: "dosa",
    iprice: "20"
  }, {
    hname: "dosa",
    iprice: "20"
  }
  // more items...
  ]
};

var html = data.hotelMitem.map(function(obj) {
  return `<tr><td>${obj.hname}</td><td>${obj.iprice}</td></tr>`;
});
$("#datatable").append(html)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="datatable"></table>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339