bootstrap-table-flat-json.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.3.0
  5. */
  6. (function ($) {
  7. 'use strict';
  8. var flat = function (element, that) {
  9. var result = {};
  10. function recurse(cur, prop) {
  11. if (Object(cur) !== cur) {
  12. result[prop] = cur;
  13. } else if ($.isArray(cur)) {
  14. for (var i = 0, l = cur.length; i < l; i++) {
  15. recurse(cur[i], prop ? prop + that.options.flatSeparator + i : "" + i);
  16. if (l == 0) {
  17. result[prop] = [];
  18. }
  19. }
  20. } else {
  21. var isEmpty = true;
  22. for (var p in cur) {
  23. isEmpty = false;
  24. recurse(cur[p], prop ? prop + that.options.flatSeparator + p : p);
  25. }
  26. if (isEmpty) {
  27. result[prop] = {};
  28. }
  29. }
  30. }
  31. recurse(element, "");
  32. return result;
  33. };
  34. var flatHelper = function (data, that) {
  35. var flatArray = [];
  36. $.each(!$.isArray(data) ? [data] : data, function (i, element) {
  37. flatArray.push(flat(element, that));
  38. });
  39. return flatArray;
  40. };
  41. $.extend($.fn.bootstrapTable.defaults, {
  42. flat: false,
  43. flatSeparator: '.'
  44. });
  45. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  46. _initData = BootstrapTable.prototype.initData;
  47. BootstrapTable.prototype.initData = function (data, type) {
  48. if (this.options.flat) {
  49. data = flatHelper(data ? data : this.options.data, this);
  50. }
  51. _initData.apply(this, [data, type]);
  52. };
  53. })(jQuery);