helper.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. module.exports = {
  2. /**
  3. * 转换数据
  4. *
  5. * @param {Array} list - 数据库查找的数据
  6. * @param {Boolean} tree - 是否展示为树形结构
  7. * @param {String} id - id属性名
  8. * @param {String} pid - pid属性名
  9. * @return {Object} - 返回转换后的数据
  10. */
  11. convertData(list, tree = true, id, pid) {
  12. const rootData = [];
  13. const childData = {};
  14. let listData = [];
  15. for (const tmp of list) {
  16. if (tmp[pid] === 0 || tmp[pid] === -1) {
  17. rootData.push(tmp);
  18. continue;
  19. }
  20. if (childData[tmp[pid]] === undefined) {
  21. childData[tmp[pid]] = [];
  22. }
  23. childData[tmp[pid]].push(tmp);
  24. }
  25. // 递归组织数据
  26. if (tree) {
  27. this._recursionTreeData(rootData, childData, id);
  28. } else {
  29. this._recursionData(rootData, childData, listData, id);
  30. }
  31. return tree ? rootData : listData;
  32. },
  33. /**
  34. * 递归组织数组结构数据
  35. *
  36. * @param {Array} parent - 父节点
  37. * @param {Object} childData - 子元素(以pid为key的对象)
  38. * @param {Array} outputData - 处理后的数据
  39. * @param {String} id - id属性名
  40. * @return {void}
  41. */
  42. _recursionData(parent, childData, outputData = [], id) {
  43. for (const index in parent) {
  44. // 父节点先进数组
  45. outputData.push(parent[index]);
  46. // 判断是否存在子项
  47. if (childData[parent[index][id]] !== undefined) {
  48. // 子项作为父节点递归查找子项中是否还有子项
  49. const tmpParent = childData[parent[index][id]];
  50. // 已用的子项删除
  51. delete childData[parent[index][id]];
  52. // 递归元素
  53. this._recursionData(tmpParent, childData, outputData);
  54. }
  55. }
  56. },
  57. /**
  58. * 递归组织树结构数据
  59. *
  60. * @param {Array} parent - 父节点
  61. * @param {Object} childData - 子元素(以pid为key的对象)
  62. * @param {String} id - id属性名
  63. * @return {void}
  64. */
  65. _recursionTreeData(parent, childData = {}, id) {
  66. if (Object.keys(childData).length <= 0) {
  67. return;
  68. }
  69. for (const index in parent) {
  70. // 判断是否存在子项
  71. if (childData[parent[index][id]] !== undefined) {
  72. // 子项作为父节点递归查找子项中是否还有子项
  73. const tmpParent = childData[parent[index][id]];
  74. // 已用的子项删除
  75. delete childData[parent[index][id]];
  76. this._recursionTreeData(tmpParent, childData);
  77. // 递归完赋值回原数据
  78. parent[index].children = tmpParent;
  79. }
  80. }
  81. }
  82. }