根据 id
和 parent_id
的对应关系,进行下面的转换。
原始数据:
1[ 2 { "id": 12, "parent_id": 1, "name": "朝阳区" }, 3 { "id": 241, "parent_id": 24, "name": "田林街道" }, 4 { "id": 31, "parent_id": 3, "name": "广州市" }, 5 { "id": 13, "parent_id": 1, "name": "昌平区" }, 6 { "id": 2421, "parent_id": 242, "name": "上海科技绿洲" }, 7 { "id": 21, "parent_id": 2, "name": "静安区" }, 8 { "id": 242, "parent_id": 24, "name": "漕河泾街道" }, 9 { "id": 22, "parent_id": 2, "name": "黄浦区" }, 10 { "id": 11, "parent_id": 1, "name": "顺义区" }, 11 { "id": 2, "parent_id": 0, "name": "上海市" }, 12 { "id": 24, "parent_id": 2, "name": "徐汇区" }, 13 { "id": 1, "parent_id": 0, "name": "北京市" }, 14 { "id": 2422, "parent_id": 242, "name": "漕河泾开发区" }, 15 { "id": 32, "parent_id": 3, "name": "深圳市" }, 16 { "id": 33, "parent_id": 3, "name": "东莞市" }, 17 { "id": 3, "parent_id": 0, "name": "广东省" } 18]
转换后的结构:
1[{ 2 "id": 2, 3 "parent_id": 0, 4 "name": "上海市", 5 "children": [{ 6 "id": 21, 7 "parent_id": 2, 8 "name": "静安区", 9 "children": [] 10 }, { 11 "id": 22, 12 "parent_id": 2, 13 "name": "黄浦区", 14 "children": [] 15 }, { 16 "id": 24, 17 "parent_id": 2, 18 "name": "徐汇区", 19 "children": [{ 20 "id": 241, 21 "parent_id": 24, 22 "name": "田林街道", 23 "children": [] 24 }, { 25 "id": 242, 26 "parent_id": 24, 27 "name": "漕河泾街道", 28 "children": [{ 29 "id": 2421, 30 "parent_id": 242, 31 "name": "上海科技绿洲", 32 "children": [] 33 }, { 34 "id": 2422, 35 "parent_id": 242, 36 "name": "漕河泾开发区", 37 "children": [] 38 }] 39 }] 40 }] 41}, { 42 "id": 1, 43 "parent_id": 0, 44 "name": "北京市", 45 "children": [{ 46 "id": 12, 47 "parent_id": 1, 48 "name": "朝阳区", 49 "children": [] 50 }, { 51 "id": 13, 52 "parent_id": 1, 53 "name": "昌平区", 54 "children": [] 55 }, { 56 "id": 11, 57 "parent_id": 1, 58 "name": "顺义区", 59 "children": [] 60 }] 61}, { 62 "id": 3, 63 "parent_id": 0, 64 "name": "广东省", 65 "children": [{ 66 "id": 31, 67 "parent_id": 3, 68 "name": "广州市", 69 "children": [] 70 }, { 71 "id": 32, 72 "parent_id": 3, 73 "name": "深圳市", 74 "children": [] 75 }, { 76 "id": 33, 77 "parent_id": 3, 78 "name": "东莞市", 79 "children": [] 80 }] 81}]