Hello! 欢迎来到小浪资源网!



如何将扁平化的数组转换成树形结构?


avatar
huizai2013 2024-11-21 20

如何将扁平化的数组转换成树形结构?

扁平化树形数组转换

问题:

如何将扁平化的数组转换为树形数组结构?

原始数组:

const arr = [     {id: 4, pid: 3},     {id: 'aa',pid:'a'},   {id: 1, pid: null},     {id: 3, pid: 2},   {id: 'a',pid: 'a0'},   {id: 2, pid: 1},   {id: 'a0',pid: null}   ];  

期望结果:

[     {         "id": 1,         "pid": null,         "children": [             {                 "id": 2,                 "pid": 1,                 "children": [                     {                         "id": 3,                         "pid": 2,                         "children": [                             {                                 "id": 4,                                 "pid": 3                             }                         ]                     }                 ]             }         ]     },     {         "id": "a0",         "pid": null,         "children": [             {                 "id": "a",                 "pid": "a0",                 "children": [                     {                         "id": "aa",                         "pid": "a"                     }                 ]             }         ]     } ]

代码实现:

arr.reduce((o, i) => {     i = Object.assign(o[i.id] ??= {}, i);     ((o[i.pid ?? ''] ??= {}).children ??= []).push(i);     return o; }, {})['']?.children

结果:

[   {     "id": 1,     "pid": null,     "children": [       {         "id": 2,         "pid": 1,         "children": [           {             "id": 3,             "pid": 2,             "children": [               {                 "id": 4,                 "pid": 3               }             ]           }         ]       }     ]   },   {     "id": "a0",     "pid": null,     "children": [       {         "id": "a",         "pid": "a0",         "children": [           {             "id": "aa",             "pid": "a"           }         ]       }     ]   } ]

相关阅读