我正面临着一个脑筋急转弯(至少对我来说):我得到一个 json 文件,其中包含一个深度的数据对象数组,如下所示:
[
{"id":1, "name":"Sport", "parent_id":0, "children":[]},
{"id":2, "name":"Tennis", "parent_id":4, "children":[]},
{"id":3, "name":"Climbing", "parent_id":5, "children":[]},
{"id":4, "name":"Indoor", "parent_id":1, "children":[]},
{"id":5, "name":"Outdoor", "parent_id":1, "children":[]},
{"id":6, "name":"Bowling", "parent_id":4, "children":[]}
]
如何将其转换为将孩子放入其父母的孩子数组中的树形结构?对象并不总是按正确的顺序排列,一个孩子在数组中可以排在它的父母之前。(如我的示例中的 id 2 和 3)
这就是我最终需要的方式:
[
{"id":1, "name":"Sport", "parent_id":0, "children":
[
{"id":4, "name":"Indoor", "parent_id":1, "children":
[
{"id":2, "name":"Tennis", "parent_id":4, "children":[]},
{"id":6, "name":"Bowling", "parent_id":4, "children":[]},
]},
{"id":5, "name":"Outdoor", "parent_id":1, "children":
[
{"id":3, "name":"Climbing", "parent_id":5, "children":[]}
]},
]}
]
知道如何实现这一目标吗?
我尝试遍历元素并将其父子数组内部推入,但是当父母被移动时,下一个兄弟姐妹再也找不到父母了......