如何根据指定key将扁平化区域数组转换为树形结构?
区域扁平化数组转指定根节点树形结构
我有一组区域数据的扁平化数组,其中最高层级区域的key为10、parent_id为null。需要将该数组重构为树形结构,当输入指定的key数组(如[10]、[1,2]、[1])时,需生成对应根节点的完整树形结构。具体示例如下:
输入数组
[ { "key": 1, "title": "Zone 1", "parent_id": 10 }, { "key": 2, "title": "Zone 2", "parent_id": 10 }, { "key": 3, "title": "Tagamo3", "parent_id": 1 }, { "key": 4, "title": "Gesr ElSuis", "parent_id": 2 }, { "key": 5, "title": "Delta", "parent_id": 2 }, { "key": 6, "title": "Mohandeseen", "parent_id": 2 }, { "key": 7, "title": "Giza", "parent_id": 1 }, { "key": 8, "title": "Helwan", "parent_id": 1 }, { "key": 9, "title": "Down Town", "parent_id": 2 }, { "key": 10, "title": "Egypt", "parent_id": null }, { "key": 11, "title": "Fayoum", "parent_id": 1 }, { "key": 12, "title": "test", "parent_id": 4 } ]
输入[10]时的树形结构与期望输出
树形结构展示
- Egypt
- Zone 1
- Tagamo3
- Giza
- Helwan
- Fayoum
- Zone 2
- Gesr ElSuis
- test
- Delta
- Mohandeseen
- Down Town
- Gesr ElSuis
期望输出
[ { "key": 10, "title": "Egypt", "parent_id": null, "children": [ { "key": 1, "title": "Zone 1", "parent_id": 10, "children": [ { "key": 3, "title": "Tagamo3", "parent_id": 1, "children": [] }, { "key": 7, "title": "Giza", "parent_id": 1, "children": [] }, { "key": 8, "title": "Helwan", "parent_id": 1, "children": [] }, { "key": 11, "title": "Fayoum", "parent_id": 1, "children": [] } ] }, { "key": 2, "title": "Zone 2", "parent_id": 10, "children": [ { "key": 4, "title": "Gesr ElSuis", "parent_id": 2, "children": [ { "key": 12, "title": "test", "parent_id": 4, "children": [] } ] }, { "key": 5, "title": "Delta", "parent_id": 2, "children": [] }, { "key": 6, "title": "Mohandeseen", "parent_id": 2, "children": [] }, { "key": 9, "title": "Down Town", "parent_id": 2, "children": [] } ] } ] } ]
输入[1,2]时的树形结构
- Zone 1
- Tagamo3
- Giza
- Helwan
- Fayoum
- Zone 2
- Gesr ElSuis
- test
- Delta
- Mohandeseen
- Down Town
- Gesr ElSuis
输入[1]时的树形结构
- Zone 1
- Tagamo3
- Giza
- Helwan
- Fayoum
内容的提问来源于stack exchange,提问作者Hussein Mohamed
相关产品推荐
相关产品推荐

