数据源

  1. [
  2. {
  3. "id": 1,
  4. "name": "办公管理",
  5. "pid": 0,
  6. "children": [
  7. {
  8. "id": 2,
  9. "name": "请假申请",
  10. "pid": 1,
  11. "children": [
  12. {
  13. "id": 4,
  14. "name": "请假记录",
  15. "pid": 2
  16. }
  17. ]
  18. },
  19. {
  20. "id": 3,
  21. "name": "出差申请",
  22. "pid": 1
  23. }
  24. ]
  25. },
  26. {
  27. "id": 5,
  28. "name": "系统设置",
  29. "pid": 0,
  30. "children": [
  31. {
  32. "id": 6,
  33. "name": "权限管理",
  34. "pid": 5,
  35. "children": [
  36. {
  37. "id": 7,
  38. "name": "用户角色",
  39. "pid": 6
  40. },
  41. {
  42. "id": 8,
  43. "name": "菜单设置",
  44. "pid": 6
  45. }
  46. ]
  47. }
  48. ]
  49. }
  50. ]

递归函数

  1. function getChildrenById(dataSource, id) {
  2. // hasFound 表示是否有找到id值
  3. let [hasFound, result] = []
  4. function findById(data) {
  5. if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下,
  6. data.forEach(item => {
  7. if (item.id === id) { // 数据循环每个子项,并且判断子项下边是否有id值
  8. result = item; // 返回的结果等于每一项
  9. hasFound = true; // 并且找到id值
  10. }
  11. else if (item.children) {
  12. findById(item.children); // 递归调用下边的子项
  13. }
  14. })
  15. }
  16. }
  17. findById(dataSource); // 调用一下
  18. return result;
  19. }

for of优化递归

  1. export const getChildrenById = (dataSource = [], id) => {
  2. let result;
  3. function findById(data) {
  4. if(result) break; // 核心点,不然会有多余的渲染
  5. // 判断是否是数组并且,数组有长度
  6. if (Array.isArray(data)) {
  7. for (const item of data) {
  8. // 数据循环每个子项,并且判断子项下边是否有id值
  9. if (item.id === id) {
  10. result = item; // 返回的结果等于每一项
  11. break;
  12. } else if (Array.isArray(item.children)) {
  13. findById(item.children); // 递归调用下边的子项
  14. }
  15. }
  16. }
  17. }
  18. findById(dataSource); // 调用一下
  19. return result;
  20. };