tree.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * 构造树型结构数据
  3. * @param {*} data 数据源
  4. * @param {*} id id字段 默认 'id'
  5. * @param {*} parentId 父节点字段 默认 'parentId'
  6. * @param {*} children 孩子节点字段 默认 'children'
  7. * @param {*} rootId 根Id 默认 0
  8. */
  9. export function handleTree(data, id, parentId, children, rootId) {
  10. id = id || 'id'
  11. parentId = parentId || 'parentId'
  12. children = children || 'children'
  13. rootId = rootId || Math.min.apply(Math, data.map(item => {
  14. return item[parentId]
  15. })) || 0
  16. //对源数据深度克隆
  17. const cloneData = JSON.parse(JSON.stringify(data))
  18. //循环所有项
  19. const treeData = cloneData.filter(father => {
  20. let branchArr = cloneData.filter(child => {
  21. //返回每一项的子级数组
  22. return father[id] === child[parentId]
  23. });
  24. branchArr.length > 0 ? father.children = branchArr : '';
  25. //返回第一层
  26. return father[parentId] === rootId;
  27. });
  28. return treeData !== '' ? treeData : data;
  29. }
  30. /**
  31. * 树形结构进行删除深度不够的分支
  32. * 目前只删除了不够三层的分支
  33. * 对于高于三层的部分目前不做处理
  34. * todo 暴力遍历,可用递归修改
  35. * @param {*} data 树形结构
  36. */
  37. export function convertTree(data) {
  38. //对源数据深度克隆
  39. const cloneData = JSON.parse(JSON.stringify(data))
  40. // 遍历克隆数据,对源数据进行删除操作
  41. for (let first = 0; first < cloneData.length; first++) {
  42. for (let second = 0; second < cloneData[first].children.length; second++) {
  43. for (let three = 0; three < cloneData[first].children[second].children.length; three++) {
  44. if (data[first].children[second].children[three].children == undefined ||
  45. data[first].children[second].children[three].children === 0) {
  46. data[first].children[second].children.splice(second, 1);
  47. }
  48. }
  49. if (data[first].children[second].children == undefined || data[first].children[second].children === 0) {
  50. data[first].children.splice(second, 1);
  51. }
  52. }
  53. if (data[first].children == undefined || data[first].children.length === 0) {
  54. data.splice(first, 1);
  55. }
  56. }
  57. return data;
  58. }