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]
2
  • for(var key in data.hotelMitem) maybe? Commented Oct 30, 2018 at 17:24
  • Why do you want to use jQuery rather than just JSON.parse(data)? Commented Oct 30, 2018 at 17:24

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

this works thank you for making it clear to me @Rory McCrossan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.