Table with dynamic column name and column count
Table with dynamic column name and column count
I have a json where in the table header name is dynamic and as well the column name is dynamic as shown below. How can I use Data table to create table for this json:
JSON:
[{
"Resource": "AAA",
"Employer": "BBB",
"MaxHours": 40,
"Allocations": [{
"AllocDate": "2019/02/17",
"AvailableHours": 0
}, {
"AllocDate": "2019/02/18",
"AvailableHours": 40
}]
}, {
"Resource": "CCC",
"Employer": "DDD",
"MaxHours": 40,
"Allocations": [{
"AllocDate": "2019/02/17",
"AvailableHours": 17
}, {
"AllocDate": "2019/02/18",
"AvailableHours": 39
}]
}]
I like the table to be displayed as:
Resource Employer MaxHours 2019/02/17 2019/02/18
AAA BBB 40 0 40
CCC DDD 40 17 39
$('table#availabilityTable').DataTable({
"data": JSON.parse(tableData),
"columns": [
{ "title":"Resource",
"data": "Resource" },
{ "title":"Employer",
"data": "Employer" },
{ "title":"MaxHours",
"data": "MaxHours" },
//Now, how to get AllocData value as column name and AllocHour as column value
//the length of 'Allocations' can change from time to time
]
});
Answers
Here is an example I created for other threads with the same question.
http://live.datatables.net/huyexejo/1/edit
It uses jQuery Ajax to fetch the data and the success function to extract the first row to build the columns. Note the use of
columns.title
to build the column headers.Kevin
Thanks @kthorngren
My question is how can I define nested json here.I tried below but it doesn't works.
success: function (data) {
//console.log(data);
data = getData();
data = JSON.parse(data);
function getAllocationColumnNames(allocations) {
var allocationColumnNames = [];
for(var i in allocations) {
allocationColumnNames[i] = allocations[i].AllocDate;
}
return allocationColumnNames;
}
function getData() {
//return above nested json
return data;
}
My suggestion would be to look on SO for a code snippet that gets the keys of a nested object. Maybe this thread as an example.
Kevin