在DataTables中显示嵌套对象的集合

时间:2015-04-21 23:26:20

标签: javascript json 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
}

我想在" DataTables"中显示上述JSON。当用户点击一行时,IssueList中的嵌套对象应显示为主表内的子表。

如何在" DataTables"?我非常陌生" DataTables"和JavaScript,并感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我不是100%肯定我会以这种方式使用Datatables。我已经做了类似的事情而不是在单元格中添加一个表格,我添加了一个定义列表...我认为否则你冒着使表格相当繁忙的风险。

但如果您确信这是您想要的方式,我会查看列上的渲染调用,并给出一个函数来创建表...或者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