Using nested object keys in row
Using nested object keys in row
mpenning
Posts: 1Questions: 1Answers: 0
Hello all,
I have been looking through examples but have not come across an example using dynamic changing keys of objects in a row and have not been able to successfully get them to work in datatables.
Here is a sample of the data:
{
"data": {
"Alice": {
"City": "Chicago",
"State": "Illinois"
},
"Bob": {
"City": "Detroit",
"State": "Michigan"
}
}
}
I am trying to get datatables to show in each row consisting of the name, city, and state but having a difficult time. I am not sure how to set the columns.data field. Any help would be much appreciated. Thanks in advance.
$('#myDataTable').DataTable({
ajax: {
url: "../api/userdata",
dataType: "json",
dataSrc: "data",
contentType: "application/json"
},
columns: [
{ title: "Name", data: "???"},
{ title: "City", data: "???"},
{ title: "State", data: "???"},
],
order: [],
});
Answers
DataTables doesn't support that format, as it expects constant keys - for you, the name is changing so DataTables wouldn't be able to find it. You can convert that object to an array, as shown in this example. Here, I'm just parsing the data before loading the table. For you, as it's coming via ajax, you would need to do that conversion in
ajax.dataSrc
(see the last example on that reference page),Colin