有如下需求:
    一个树形结构:

    1. const data = [
    2. {
    3. "id": 1,
    4. "name": "test0",
    5. "children": [
    6. {
    7. "id": 3,
    8. "name": "test01",
    9. "parent": {
    10. "id": 1,
    11. "name": "test0"
    12. },
    13. "children": [
    14. {
    15. "id": 8,
    16. "name": "test011",
    17. "children": [],
    18. "parent": {
    19. "id": 3,
    20. "name": "test01"
    21. }
    22. },
    23. {
    24. "id": 9,
    25. "name": "test012",
    26. "children": [],
    27. "parent": {
    28. "id": 3,
    29. "name": "test01"
    30. }
    31. },
    32. {
    33. "id": 10,
    34. "name": "test013",
    35. "node_order": 2,
    36. "children": [],
    37. "parent": {
    38. "id": 3,
    39. "name": "test01"
    40. }
    41. }
    42. ]
    43. },
    44. {
    45. "id": 6,
    46. "name": "test02",
    47. "children": [
    48. {
    49. "id": 14,
    50. "name": "test021"
    51. },
    52. {
    53. "id": 15,
    54. "name": "test022"
    55. }
    56. ]
    57. }
    58. ]
    59. },
    60. {
    61. "id": 2,
    62. "name": "test1",
    63. "children": [
    64. {
    65. "id": 5,
    66. "name": "test11",
    67. "children": [
    68. {
    69. "id": 11,
    70. "name": "test111"
    71. },
    72. {
    73. "id": 12,
    74. "name": "test112"
    75. },
    76. {
    77. "id": 13,
    78. "name": "test113",
    79. "node_order": 2
    80. }
    81. ]
    82. },
    83. {
    84. "id": 7,
    85. "name": "test12",
    86. "children": [
    87. {
    88. "id": 16,
    89. "name": "test121"
    90. },
    91. {
    92. "id": 17,
    93. "name": "test122"
    94. }
    95. ]
    96. }
    97. ]
    98. }
    99. ]


    需要从中遍历出id值为[ 3,6 ]的数据。

    1. // 获取所有父级
    2. function getTreeParents(tree=[], ids=[]) {
    3. const currentMenu = ids.map(m => {
    4. var stark = [];
    5. stark = stark.concat(tree);
    6. while(stark.length) {
    7. var temp = stark.shift();
    8. if(temp.children) {
    9. stark = stark.concat(temp.children);
    10. }
    11. if(temp.id === m) {
    12. return temp;
    13. }
    14. }