JS Nested Object Data format
JS Nested Object Data format
Hi,
I'm trying to use a json format to populate a table and not having any luck. The data format is below . I tried using this example but it simply didn't work for my situation. Not sure why: https://datatables.net/examples/ajax/deep.html
var data = [
{
name: "index1",
data: [
{
name: 'Cash',
y: 35.61
}, {
name: 'Net Derivatives',
y: 12.79
}, {
name: 'Non-US Sovereign Related',
y: 11.77
}, {
name: 'Emerging Markets',
y: 6.59
}, {
name: 'Agency Pass-Through MBS',
y: 6.55
}, {
name: 'Commercial Mortgages',
y: 5.97
}, {
name: 'Asset Backed Securities',
y: 5.4
}
]
},
{
name: "index2",
data: [
{
name: 'Cash',
y: 35.61
}, {
name: 'Net Derivatives',
y: 12.79
}, {
name: 'Non-US Sovereign Related',
y: 11.77
}, {
name: 'Emerging Markets',
y: 6.59
}, {
name: 'Agency Pass-Through MBS',
y: 6.55
}, {
name: 'Commercial Mortgages',
y: 5.97
}, {
name: 'Asset Backed Securities',
y: 5.4
}
]
},
{
name: "index",
data: [
{
name: 'Cash',
y: 35.61
}, {
name: 'Net Derivatives',
y: 12.79
}, {
name: 'Non-US Sovereign Related',
y: 11.77
}, {
name: 'Emerging Markets',
y: 6.59
}, {
name: 'Agency Pass-Through MBS',
y: 6.55
}, {
name: 'Commercial Mortgages',
y: 5.97
}, {
name: 'Asset Backed Securities',
y: 5.4
}
]
}
];
The table has 4 columns with the first column using one set of the object name values, i.e. not repeated. The second, third and fourth columns would have the y values from index1, index2 and index3 respectively.
And here is how I am trying to configure it (I left out the other options not relevant here):
var tableOptions = {
"columns" = [
{ "data": "0.data.name" },
{ "data": "0.data.y" },
{ "data": "1.data.y" },
{ "data": "2.data.y" }
],
"data": tableData
}
$table.DataTable( tableOptions );
Any suggestions are appreciated.
This question has an accepted answers - jump to answer
Answers
Hi,
I'm afraid DataTables can't use the JSON data in that form. It needs each item in the array to be an individual row - whereas with the structure above you've got information for multiple different rows in each array element.
It would need to be transposed into an array with an element for each row you want to display. Given you are passing it in to
data
you could just do that transposition before initialising the DataTable.Regards,
Allan
Thanks Allan. Appreciate the quick answer and the guidance.