Data Tables - Using Column Names Instead of Indexes

I have DataTables as shown below.

var pageData = [ { "id":"2", "slug":"about\/history", "title":"History", "last_updated":"2013-04-21 09:50:41" }, { "id":"3", "slug":"about", "title":"About", "last_updated":"2013-04-21 10:42:22" } ]; $(function () { $("#pageList").dataTable({ "aaData" : pageData, "aoColumns" : [ { "sTitle" : "slug" }, { "sTitle" : "title" }, { "sTitle" : "last_updated" }, { "sTitle" : "id" } ] }); }); 

Now that I run this, I get the following error message

 DataTables warning (table id = 'pageList'): Requested unknown parameter '0' from the data source for row 0 

And I guess this is because datatables uses indexes instead of column names to access data from pageData . I thought sTitle would do the job, but it is not. Now I cannot find a suitable option for specifying column names on a datatable, except for sName , which is used only when sending data to the server.

I feel that the solution will be simple, which I missed. Well, what am I missing here?

+4
source share
1 answer

jQuery datatable accepts data as an array of arrays. Therefore, you need to convert your data from an array of objects to an array of arrays.

 var pageData = [{ "id": "2", "slug": "about\/history", "title": "History", "last_updated": "2013-04-21 09:50:41" }, { "id": "3", "slug": "about", "title": "About", "last_updated": "2013-04-21 10:42:22" }]; var aaPageData = []; for (var i = 0; i < pageData.length; i++) { var item = pageData[i]; aaPageData[i] = [item.slug, item.title, item.last_updated, item.id]; } $(document).ready(function () { $("#table").dataTable({ "aaData": aaPageData, "aoColumns": [{ "sTitle": "slug", }, { "sTitle": "title" }, { "sTitle": "last_updated" }, { "sTitle": "id" }] }); }); 

demo: http://jsfiddle.net/BYcsk/

EDIT: No need to convert. You can achieve this by specifying the mData property for the columns. The error goes as you did not give it.

 var pageData = [{ "id": "2", "slug": "about\/history", "title": "History", "last_updated": "2013-04-21 09:50:41" }, { "id": "3", "slug": "about", "title": "About", "last_updated": "2013-04-21 10:42:22" }]; $(document).ready(function () { $("#table").dataTable({ "aaData": pageData, "aoColumns": [{ "sTitle": "slug", "mData": "slug" }, { "sTitle": "title", "mData": "title" }, { "sTitle": "last_updated", "mData": "last_updated" }, { "sTitle": "id", "mData": "id" }] }); }); 

demo: http://jsfiddle.net/BYcsk/3/

+3
source

All Articles