user3093010 user3093010 - 4 months ago 12
jQuery Question

Can't create dynamic table from JSON

How I can create dynamic table with JQuery from these object

Object is array type and store every column data.

I want table like this:

+--Start_Hour--Start_Minutes--Start_Month--+
| 11 | 00 | 07 --|
| 03 | 03 | 03 --|


enter image description here

Yes, but its bad code :(

function GenerateHolidayTable(data) {
var name, number;
var HolidayTableHTML = '';
HolidayTableHTML += '<table class="table"><tr><th>Start_Month</th><th>Start_Day</th><th>Start_Hour</th><th>Start_Min</th><th>End_Month</th><th>End_Day</th><th>End_Hour</th><th>End_Min</th> <th>Description</th></tr>';
$.each(data, function(key, value) {
if (key == "Start_Month") {
HolidayTableHTML += '<tr>';
$.each(value, function(key, value) {
HolidayTableHTML += '<td>' + value + ' </td>';
});
}
..................................
else if (key == "Description") {
$.each(value, function(key, value) {
HolidayTableHTML += '<td>' + value + ' </td>';
});
HolidayTableHTML += '</tr>';
}
});
HolidayTableHTML += '</table>';
$('#HolidayTable').append(HolidayTableHTML);
}

Answer

You can do something like this :

Assuming all the three (Start_Month,Start_Hour & Start_Minutes) will have equal length.

var json = "{\"Start_Month\": {\"1\" :\"1\",\"2\" :\"2\",\"3\" :\"3\"},\"Start_Minutes\": {\"1\" :\"10\",\"2\" :\"20\",\"3\" :\"30\"},\"Start_Hour\": {\"1\" :\"01\",\"2\" :\"02\",\"3\" :\"03\"}}";
var jsonObj = JSON.parse(json);
$.each(jsonObj.Start_Hour, function(idx, val) {
  var row = "<tr>";
  row += "<td>" + val + "</td>";
  row += "<td>" + jsonObj.Start_Minutes[idx] + "</td>";
  row += "<td>" + jsonObj.Start_Month[idx] + "</td>";
  row += "</tr>";
  $("#data").append(row);
});
table {
  width: 100%;
}
table,
td,
th {
  border: 2px lightblue solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Start_Hour</th>
      <th>Start_Minutes</th>
      <th>Start_Month</th>
    </tr>
  </thead>
  <tbody id="data"></tbody>
</table>

Comments