east1999
east1999

Reputation: 199

Datatables with nested array

I've posed a question about Bootstrap Tables but meanwhile I moved to Datatables as I was feeling blocked. My problem, however, is the same.

None of the two can easily handle nested JSON results. For instance if I choose "field: author", it processes the following as "[Object Object], [Object Object]".

    "author": [
        {
            "family": "Obama",
            "given": "Barack"
        },
        {
            "family": "Obama",
            "given": "Michelle"
        }

I can select the results individually, say "field: author[, ].family", which returns a list like "Obama, Obama". But I want an output like "given+family1, given+family2, ..".

Upvotes: 1

Views: 4484

Answers (1)

Deven Shah
Deven Shah

Reputation: 422

You can use custom rendering. DataTables allows you to define custom rendering for each column.

Here is a sample that I worked out. I am doing custom rendering for Author column.

$(document).ready(function() {
var dataSet = [
    { "name": "How to DataTables", "author": [{ "firstname": "jack", lastname: "d" }, { "firstname": "dick", lastname: "j" }] },
    { "name": "How to Custom Render", "author": [{ "firstname": "bill", lastname: "g" }, { "firstname": "scott", lastname: "g" }] }
];

$('#example').DataTable({
    data: dataSet,
    columns: [
        { title:"Book Name",
          data: "name" },
        {
          title: "Authors",
            data: "author",
            render: function(data, type, row) {
                //return data.length;
                var txt = '';
                data.forEach(function(item) {
                    if (txt.length > 0) {
                      txt += ', '
                    }
                    txt += item.firstname + ' ' + item.lastname;
                });
                return txt;
            }
        }
    ]
});
});

Upvotes: 3

Related Questions