【发布时间】:2014-12-03 08:47:39
【问题描述】:
我有一个带有子字段的“页面”对象列表。此子字段引用列表中的另一个对象。我想根据这个字段从这个列表中创建一个树层次结构。 我找到了一个解决方案here,但它只有在我有父字段时才有效。这是我的原始列表的样子:
[
{
id: 1,
title: 'home',
child: null
},
{
id: 2,
title: 'about',
child: null
},
{
id: 3,
title: 'team',
child: 4
},
{
id: 4,
title: 'company',
child: 2
}
]
我想把它转换成这样的树形结构:
[
{
id: 1,
title: 'home',
},
{
id: 3,
title: 'team',
children: [
{
id: 4,
title: 'company',
children: {
id: 2,
title: 'about',
}
}
]
]
我希望有一个可重用的函数,我可以随时针对任意列表调用它。有人知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!
【问题讨论】:
标签: javascript arrays tree hierarchy