treeTools.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*jshint esversion: 9 */
  2. /**
  3. * 用于处理目录的工具
  4. */
  5. /**
  6. * 将目录转换为树形结构
  7. */
  8. export function toTree(
  9. list = [],
  10. option = { key: 'id', pKey: 'pid', isNew: true, childsKey: 'childs' },
  11. ) {
  12. const { key, pKey, isNew, childsKey } = option;
  13. if (isNew) {
  14. list = JSON.parse(JSON.stringify(list));
  15. }
  16. const idMap = {};
  17. const tree = [];
  18. list.forEach((item) => {
  19. idMap[item[key]] = item;
  20. });
  21. list.forEach((item) => {
  22. if (idMap[item[pKey]]) {
  23. idMap[item[pKey]][childsKey] = idMap[item[pKey]][childsKey] || [];
  24. idMap[item[pKey]][childsKey].push(item);
  25. } else {
  26. tree.push(item);
  27. }
  28. });
  29. return tree;
  30. }
  31. /**
  32. * 展开树形list结构为一维list
  33. * @param treeList:array
  34. * @param option:object
  35. */
  36. export function unfoldTreeList(treeList, option = {}) {
  37. const {
  38. childsKey = 'children', //需要获取子元素的 key
  39. setParentKey = 'parentId', //需要赋值的父元素 key
  40. getParentKey = 'id', //获取父元素 key
  41. forEachFn = null, //循环时的回调
  42. } = option;
  43. const deptOneList = [];
  44. const deepForEach = (target) => {
  45. deptOneList.push(target);
  46. forEachFn && forEachFn(target);
  47. if (target[childsKey]) {
  48. target[childsKey].forEach((item_) => {
  49. item_[setParentKey] = target[getParentKey];
  50. deepForEach(item_);
  51. });
  52. }
  53. };
  54. treeList.forEach((item) => {
  55. deepForEach(item);
  56. });
  57. return deptOneList;
  58. }