bootstrap-table-group-by.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.0.0
  5. */
  6. !function ($) {
  7. 'use strict';
  8. var setObjectKeys = function () {
  9. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  10. Object.keys = function(o) {
  11. if (o !== Object(o)) {
  12. throw new TypeError('Object.keys called on a non-object');
  13. }
  14. var k=[],p;
  15. for (p in o) {
  16. if (Object.prototype.hasOwnProperty.call(o,p)) {
  17. k.push(p);
  18. }
  19. }
  20. return k;
  21. }
  22. };
  23. var groupBy = function (array , f) {
  24. var groups = {};
  25. array.forEach( function(o) {
  26. var group = JSON.stringify(f(o));
  27. groups[group] = groups[group] || [];
  28. groups[group].push(o);
  29. });
  30. return Object.keys(groups).map(function (group) {
  31. return groups[group];
  32. });
  33. };
  34. $.extend($.fn.bootstrapTable.defaults, {
  35. groupBy: false,
  36. groupByField: ''
  37. });
  38. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  39. _init = BootstrapTable.prototype.init,
  40. _initData = BootstrapTable.prototype.initData;
  41. BootstrapTable.prototype.init = function () {
  42. _init.apply(this, Array.prototype.slice.apply(arguments));
  43. /*if (!this.options.groupBy) {
  44. return;
  45. }*/
  46. // Compatibility: IE < 9 and old browsers
  47. if (!Object.keys) {
  48. setObjectKeys();
  49. }
  50. };
  51. BootstrapTable.prototype.initData = function () {
  52. _initData.apply(this, Array.prototype.slice.apply(arguments));
  53. /*if ((!this.options.groupBy) || (this.groupByName === '')) {
  54. return;
  55. }*/
  56. var that = this;
  57. //**TESTING**
  58. this.options.groupByField = 'name';
  59. console.log(this.options.data);
  60. var result = groupBy(this.options.data, function(item) {
  61. return [item[that.options.groupByField]];
  62. });
  63. console.log(result);
  64. //**TESTING**
  65. };
  66. }(jQuery);