我有一个包含parent
字段的“页面”对象列表。这个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
}
]
我想将它转换成这样的树形结构:
[
{
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
}
]
]
我希望有一个可重用的函数,可以随时对任意列表进行调用。有人知道如何处理这个问题吗?任何帮助或建议将不胜感激!
O(2n) = O(n)
。我的解决方案也是O(n)
。我承认我没有创造速度记录。无论是我的版本还是你的版本更快,都可以测量(两个简单循环与一个复杂循环),但我不能事先确定哪个更快。然而,它们的时间复杂度完全相同。 - Amadanperformant-array-to-tree
的下载量,因此我编写了一些基准测试,以测试npm上某些可用包的性能。请在此处查看结果:https://github.com/philipstanislaus/array-to-tree-benchmarks。如果您有兴趣,我们很乐意添加其他内容! - Philip Stanislaus