I have the following json which is a response from ajax call.
[
{
"Key1":"value1",
"key2":{
"subkey1":"subvalue",
"subkey2":"subvalue2"
}
},
{
"Key1":"value1",
"key2":{
"subkey1":"subvalue3",
"subkey2":"subvalue4"
}
}
]
I have to display values of key 2 in html table.
subkey1 subkey2
--------- ---------
subvalue1 subvalue2
subvalue3 subvalue4
Please note that number of columns are also dynamic.
You can get the keys from first object with Object.keys()
to set the header. Then loop through the array with each()
to set the table body.
Try the following way:
var arrData = [ { "Key1":"value1", "key2":{ "subkey1":"subvalue1", "subkey2":"subvalue2" } }, { "Key1":"value1", "key2":{ "subkey1":"subvalue3", "subkey2":"subvalue4" } } ] var col = Object.keys(arrData[0].key2); $('table').append('<thead><tr><th>' +col[0]+'</th><th>' +col[1]+'</th></tr></thead>'); $(arrData).each(function(i,v){ $('#tbody').append('<tr><td>' +v.key2.subkey1+'</td><td>' +v.key2.subkey2+'</td>'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody id="tbody"></tbody> </table>
var response = [
{
"Key1":"value1",
"key2":{
"subkey1":"subvalue",
"subkey2":"subvalue2"
}
},
{
"Key1":"value1",
"key2":{
"subkey1":"subvalue3",
"subkey2":"subvalue4"
}
}
];
var columns = [];
if(response.length >0) {
var item = response[0];
columns = Object.keys(item['key2']);
}
var htmlStr = '<table><tr>';
columns.map(function(col){
htmlStr += '<th>'+col+'</th>';
});
htmlStr += '</tr>';
response.map(function(item){
htmlStr += '<tr>';
columns.map(function(colName){
htmlStr += '<td>' + item.key2[colName]+'</td>';
});
htmlStr += '</tr>';
});
document.getElementById('table').innerHTML = htmlStr + '</table>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.