I'm displaying JSON data in a tabular format on a html page using jQuery.
In the function I'm looping the resp.DATA
once to get the key names so it can be displayed as the headings in the table, and a second time to get the values of the keys for all customers.
Can this be done in a way that I only have to loop the resp.DATA
once?
JSON data:
var resp= {
"ERROR": [],
"DATA": [{
"CustomerID": "234",
"BranchID": "1",
"LocationID": "26",
"FirstName": "Lakshmi "
}, {
"CustomerID": "235",
"BranchID": "1",
"LocationID": "6",
"FirstName": "Arora "
}, {
"CustomerID": "236",
"BranchID": "1",
"LocationID": "68",
"FirstName": "S.K.Raman "
}, {
"CustomerID": "237",
"BranchID": "1",
"LocationID": "38",
"FirstName": "Vidya Rao "
}, {
"CustomerID": "238",
"BranchID": "1",
"LocationID": "18",
"FirstName": "Raju "
}, {
"CustomerID": "239",
"BranchID": "1",
"LocationID": "49",
"FirstName": "K.B.Hebbar "
}],
"META": {
"currentPageNumber": "1",
"totalPages": "11",
"rowcountCurrentPage": "10",
"rowcountTotal": "107"
}
}
Code:
var content = '<table class="table table-hover">';
var heading = "<tr>";
var data = "";
$.each(resp.DATA[0], function(ke, va) {
heading += '<th>' + ke + '</th>';
});
$.each(resp.DATA, function(key, value) {
data += "<tr>";
$.each(value, function(k, v) {
data += '<td>' + v + '</td>';
});
data += "</tr>";
});
heading += "</tr>";
content += heading + data + "</table>";
$('#data').append(content);
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>COnsuming rest webservice</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head>
<body>
<h1>Consuming REST api</h1>
<div class="container">
<div id="data"> </div>
</div>
<!-- <input type="button" id="driver" value="Load Data" /> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</script>
</body>
</html>
You can see a working example here.