Holt59 / datatable

Javascript Plugin for data tables creation
http://holt59.github.io/datatable/
MIT License
109 stars 43 forks source link

Generate thead for data objects #13

Open belg4mit opened 9 years ago

belg4mit commented 9 years ago

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 commented 9 years ago

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;
                     }