datatable icon indicating copy to clipboard operation
datatable copied to clipboard

Generate thead for data objects

Open belg4mit opened this issue 10 years ago • 1 comments

If data: is an array of objects, use the object keys to create the table header for use in labeling, as well as sorting.

belg4mit avatar Jun 12 '15 13:06 belg4mit

Below is a patch to implement this behavior, although it may not be the most elegant approach. However, sorting does not seem to work. The column style changes when the header is clicked, but the table contents are not sorted to match. Filters do not function correctly either.

--- /tmp/datatable.js   2015-06-06 09:31:15.000000000 -0400
+++ datatable.js        2015-06-12 09:44:30.347206300 -0400
@@ -29,9 +29,17 @@

         var dataTable = this;

+        if ($.isArray(this.options.data)) {
+            this.data = this.options.data;
+        }
+ 
+
         if (this.table.find('thead').length === 0) {
             var head = $('<thead></thead>');
-            head.append(this.table.find('th').parent('tr'));
+            var row = head.append($("<tr/>"));
+           $.each(Object.keys(this.data[0]), function(colIndex, c) {
+              row.append($("<th/>").text(c));
+           });
             this.table.prepend(head);
         }

@@ -40,7 +48,7 @@
         }

         if ($.isArray(this.options.data)) {
-            this.data = this.options.data;
+            //this.data = this.options.data;
         }
         else if ($.isPlainObject(this.options.data)) {
             if (this.table.data('size')) {
@@ -973,7 +981,6 @@
                 var countTH = 0;

                 this.table.find('thead th').each(function () {
-
                     if ($(this).data('sort')) {
                         dataTable.options.sort = true;
                     }

belg4mit avatar Jun 12 '15 13:06 belg4mit