求助!如何将一维数组变成多维数组

169 阅读1分钟

有如下数组:

 { type: "Case", id: 1001, parent_id: null }, 
 { type: "Step", id: 1002, parent_id: 1001}, 
 { type: "Case", id: 1003, parent_id: 1002}, 
 { type: "Step", id: 1004, parent_id: 1003}, 
 { type: "Func", id: 1005, parent_id: 1004}, 
 { type: "Func", id: 1006, parent_id: 1004},
 { type: "Func", id: 1007, parent_id: 1004},
 { type: "Func", id: 1008, parent_id: 1004},
 { type: "Func", id: 1009, parent_id: 1004}, 
 { type: "Func", id: 1010, parent_id: 1004},
 { type: "Func", id: 1011, parent_id: 1004},
 { type: "Func", id: 1012, parent_id: 1004},
 { type: "Func", id: 1013, parent_id: 1002 }
]```


如何将上述数组转变成下列数组呢?


```[{
  type: "Case",
  id: 1001,
  parent_id: null,
  children: [{
    type: "Step",
    id: 1002,
    parent_id: 1001,
    children: [{
        type: "Case",
        id: 1003,
        parent_id: 1002,
        children: [{
          type: "Step",
          id: 1004,
          parent_id: 1003,
          children: [
            { type: "Func", id: 1005, parent_id: 1004 },
            { type: "Func",  id: 1006, parent_id: 1004 },
            { type: "Func", id: 1007, parent_id: 1004 },
            { type: "Func", id: 1008, parent_id: 1004 },
            { type: "Func", id: 1009, parent_id: 1004 },
            { type: "Func", id: 1010, parent_id: 1004 },
            { type: "Func", id: 1011, parent_id: 1004 },
            { type: "Func", id: 1012, parent_id: 1004 }
          ]
        }, ]
      },
      { type: "Func", id: 1013, parent_id: 1002 },
      { type: "Func", id: 1013, parent_id: 1002 }
    ]
  }]
}] ```

**注:数组还可能有更多层次**