我有一个带有parent
字段的"页面"对象列表.此父字段引用列表中的另一个对象.我想基于此字段从此列表中创建树层次结构.
这是我的原始列表:
[
{
id: 1,
title: 'home',
parent: null
},
{
id: 2,
title: 'about',
parent: null
},
{
id: 3,
title: 'team',
parent: 2
},
{
id: 4,
title: 'company',
parent: 2
}
]
Run Code Online (Sandbox Code Playgroud)
我想将它转换为这样的树结构:
[
{
id: 1,
title: 'home',
parent: null
},
{
id: 2,
title: 'about',
parent: null,
children: [
{
id: 3,
title: 'team',
parent: 2
},
{
id: 4,
title: 'company',
parent: 2
}
]
]
Run Code Online (Sandbox Code Playgroud)
我希望有一个可重用的函数,我可以随时调用任意列表.有人知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!