Harrison Harrison - 3 months ago 26
Javascript Question

How to read information from deeply nested objects in Datatables?

I have json in this format:

[
{"aaa":"aaa"},
{"Columns":[
[{"bbb":"bbbb"}, {"name":"name1"}, {"gender":"gender1"}],
[{"bbb":"bbbb"}, {"name":"name2"}, {"gender":"gender2"}],
]}
]


I tried:

$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/file.txt",
"columns": [
{ "data": "Columns.0.name" },
{ "data": "Columns.0.gender" },
]
} );
} );


but it gave me an error:
Uncaught TypeError: Cannot read property 'length' of undefined

How should I read
name
and
gender
? Thanks.

Answer

Use the code below:

var table = $('#example').DataTable({
    ajax: {
       url: 'https://api.myjson.com/bins/2p254',
       dataSrc: '1.Columns'
    },
    columns: [
        { "data": '0.name' },
        { "data": '0.gender' }
    ]        
});

See this jsFiddle for code and demonstration.