Nested JSON

Nested JSON

mihixay693mihixay693 Posts: 1Questions: 1Answers: 0

I am using Mongodb which has embedded documents and trying to display the embedded document into the same table.

My Sample data:

data = {
        "data": [
            {
                "id": "1",
                "name": "John Q Public",
                "office": "Edinburgh",
                "extn": "5421",
                "hr": [
                    {
                        "position": "System Architect",
                        "salary": "$3,120",
                    },
                    {
                        "position": "System",
                        "salary": "$3,120",
                    }
                ]
            },
            {
                "id": "2",
                "name": "Larry Bird",
                "office": "Tokyo",
                "extn": "8422",
                "hr":
                    {
                        "position": "test",
                        "salary": "$320",
                    }
            }]
    }
$(document).ready(function () {
    $('#example').DataTable({
        "ajax": {
            // "url": "static/objects2.txt", // This works for the static file
            "url": "/index_get_data",
            "dataSrc": "data"
        },
        "columns": [
            {"data": "name"},
            {"data": "office"},
            {"data": "extn"},
            {"data": "hr.salary"}
        ]
    });
});
<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Salary</th>
            </tr>
        </tfoot>
</table>

My Output:

I am new to Datatables and don't know if this even possible?

Answers

  • kthorngrenkthorngren Posts: 21,166Questions: 26Answers: 4,921

    For John Q Public the hr object is an array of objects where for Larry Bird its a single object. If your data structure for that column is not consistent then you can use columns.render to either display the salary if its an object or iterate the array and display one or more of the salary objects in the array.

    Kevin

This discussion has been closed.