Jackson Jegatheesan
Jackson Jegatheesan

Reputation: 668

How to extract data from json array with jquery and append it in html table?

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

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]

Upvotes: 2

Views: 183

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

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>

Upvotes: 2

Related Questions