RDs
RDs

Reputation: 521

Display collection of nested objects in DataTables

[
{
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "/Date(1429653550233)/",
    "IssueList": null
},
{
    "name": "Tiger Nixon 1",
    "position": "System Architect 1",
    "salary": "$420,800",
    "start_date": "2011/04/25",
    "IssueList": [
        {
            "Number": 1,
            "IssueDate": "/Date(1429653550233)/",
            "Issue": "Lots of Problems"
        },
        {
            "Number": 2,
            "IssueDate": "/Date(1429185060000)/",
            "Issue": "Lots of Problems here too"
        }
    ]
},
{
    "name": "Tiger Nixon 2",
    "position": "System Architect 2",
    "salary": "$520,800",
    "start_date": "2011/04/25",
    "IssueList": [
        {
            "Number": 3,
            "IssueDate": "/Date(1429653550233)/",
            "Issue": "Lots of Problems"
        },
        {
            "Number": 4,
            "IssueDate": "/Date(1429185060000)/",
            "Issue": "Lots of Problems here too"
        }
    ]
},
{
    "name": "Tiger Nixon 3",
    "position": "System Architect 3",
    "salary": "$620,800",
    "start_date": "2011/04/25",
    "IssueList": null
}

]

I want to display the above JSON in "DataTables". The nested objects in the IssueList should be displayed as a child table inside the main table when the user clicks on a row.

How can this be done in "DataTables"? I am very new to "DataTables" and JavaScript and would appreciated your help.

Upvotes: 1

Views: 3322

Answers (1)

annoyingmouse
annoyingmouse

Reputation: 5689

I'm not 100% sure I'd use Datatables in this way. I've done something similar but rather than adding a table in a cell I've added a definition list... I think otherwise you're running the risk of making the table rather busy.

But if you're convinced that this is the way you want to go I'd look at the render call on the column and give is a function to create a table... or dl...

$("#myTable").DataTable({
    "data": data,
    "columns": [
        { 
            "title": "Name",
            "data": "name"
        }, { 
            "title": "Position",
            "data": "position" 
        }, { 
            "title": "Salary",
            "data": "salary" 
        }, { 
            "title": "Start Date",
            "data": "start_date" 
        }, { 
            "title": "Issue List",
            "data": "IssueList",
            "render": function(d){
                if(d !== null){
                    var table = "<table>";
                    $.each(d, function(k, v){
                        table += "<tr><td>" + v.Issue + "</td><td>" + v.IssueDate + "</td><td>" + v.Number + "</td></tr>";
                    });
                    return table + "</table>";
                }else{
                    return "";
                }
            }
        }
    ]
});

Working Example

Upvotes: 3

Related Questions