扁平化数组转换成树形?
背景:
需要将扁平化数组转换成树形数组。
比如原始数组如下:
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"
}
]
}
]
}
]
回复
1个回答

test
2024-06-19
js
代码
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"
}
]
}
]
}
]
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容