我有一个带有子字段的“页面”对象列表。该子字段引用列表中的另一个对象。我想根据该字段从该列表创建一个树层次结构。 我找到了解决方案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',
}
}
]
]
我希望有一个可重用的函数,我可以随时调用任意列表。有人知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!
最佳答案
找到了一个解决方案,使用Underscore.js添加父项,然后使用this solution
_.each(flat, function (o) {
o.child.forEach(function (childId) {
_.findWhere(flat, {id: childId}).parent = o.id;
});
});
关于javascript - 从带有子字段的平面列表构造层次结构树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267178/