获取对象嵌套

  1. const a = {
  2. b: 1,
  3. c() {},
  4. d: {
  5. e: 2,
  6. f: {
  7. g: 3,
  8. h: {
  9. i: {
  10. j: 5
  11. },
  12. },
  13. },
  14. j: {
  15. k: 5,
  16. },
  17. },
  18. };
  19. // 箭头函数命名方式
  20. const testLevel = (param => {
  21. const isObject = Object.prototype.toString.call(param) === '[object Object]';
  22. if (!isObject) return 0;
  23. const level = 1;
  24. let childrenLevel = 0;
  25. Object.entries(param)
  26. .map(([key, value]) => {
  27. const valueLevel = testLevel(value, level);
  28. if (valueLevel > childrenLevel) childrenLevel = valueLevel;
  29. });
  30. num = level + childrenLevel
  31. return level + childrenLevel;
  32. })
  33. testLevel(a)
  34. console.log(num)
  35. let num

获取数组嵌套

  1. const treeData=[{
  2. "label": "广东省",
  3. "children": [{
  4. "label": "梅州市",
  5. "children": [{
  6. "label": "兴宁市",
  7. "children": [{
  8. "label": "黄槐镇",
  9. "children": [{
  10. "label": "西埔村",
  11. "children": []
  12. },
  13. {
  14. "label": "宝龙村",
  15. "children": []
  16. },
  17. {
  18. "label": "双下村",
  19. "children": []
  20. },
  21. {
  22. "label": "双头村",
  23. "children": []
  24. },
  25. {
  26. "label": "槐东村",
  27. "children": []
  28. }
  29. ]
  30. }]
  31. }]
  32. }]
  33. }, {
  34. "label": "一级2",
  35. "children": []
  36. }, {
  37. "label": "一级3",
  38. "children": []
  39. }]
  40. function getMaxFloor (treeData) {
  41. let floor = 0
  42. let v = this
  43. let max = 0
  44. function each (data, floor) {
  45. data.forEach(e => {
  46. e.floor = floor
  47. if (floor > max) {
  48. max = floor
  49. }
  50. if (e.children.length > 0) {
  51. each(e.children, floor + 1)
  52. }
  53. })
  54. }
  55. each(treeData,1)
  56. return max
  57. }