bootstrap-table-flat-json.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.1.0
  5. */
  6. (function ($) {
  7. 'use strict';
  8. var flatJSON = function (el, data) {
  9. if (el.options.flat) {
  10. el.options.data = sd.flatHelper(data);
  11. }
  12. if (el.options.sidePagination === 'server') {
  13. el.data = el.options.data;
  14. }
  15. };
  16. $.extend($.fn.bootstrapTable.defaults, {
  17. flat: false
  18. });
  19. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  20. _initData = BootstrapTable.prototype.initData,
  21. _init = BootstrapTable.prototype.init,
  22. _initTable = BootstrapTable.prototype.initTable;
  23. BootstrapTable.prototype.initData = function (data) {
  24. _initData.apply(this, Array.prototype.slice.apply(arguments));
  25. flatJSON(this, data === undefined ? this.options.data : data);
  26. };
  27. BootstrapTable.prototype.init = function () {
  28. flatJSON(this, this.options.data);
  29. _init.apply(this, Array.prototype.slice.apply(arguments));
  30. };
  31. BootstrapTable.prototype.initTable = function () {
  32. flatJSON(this, this.options.data);
  33. _initTable.apply(this, Array.prototype.slice.apply(arguments));
  34. };
  35. //Main functions
  36. var sd = {
  37. flat: function (element) {
  38. var result = {};
  39. function recurse(cur, prop) {
  40. if (Object(cur) !== cur) {
  41. result[prop] = cur;
  42. } else if ($.isArray(cur)) {
  43. for (var i = 0, l = cur.length; i < l; i++) {
  44. recurse(cur[i], prop ? prop + "." + i : "" + i);
  45. if (l == 0) {
  46. result[prop] = [];
  47. }
  48. }
  49. } else {
  50. var isEmpty = true;
  51. for (var p in cur) {
  52. isEmpty = false;
  53. recurse(cur[p], prop ? prop + "." + p : p);
  54. }
  55. if (isEmpty) {
  56. result[prop] = {};
  57. }
  58. }
  59. }
  60. recurse(element, "");
  61. return result;
  62. },
  63. flatHelper: function (data) {
  64. var flatArray = [],
  65. arrayHelper = [];
  66. if (!$.isArray(data)) {
  67. arrayHelper.push(data);
  68. data = arrayHelper;
  69. }
  70. $.each(data, function (i, element) {
  71. flatArray.push(sd.flat(element));
  72. });
  73. return flatArray;
  74. }
  75. };
  76. })(jQuery);