javascript – 使用父字段从平面列表构建层次结构树?

前端之家收集整理的这篇文章主要介绍了javascript – 使用父字段从平面列表构建层次结构树?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有父字段的“页面”对象的列表.此父字段引用列表中的另一个对象.我想从这个列表中创建一个树层次结构.

这是我的原始列表的样子:

  1. [
  2. {
  3. id: 1,title: 'home',parent: null
  4. },{
  5. id: 2,title: 'about',{
  6. id: 3,title: 'team',parent: 2
  7. },{
  8. id: 4,title: 'company',parent: 2
  9. }
  10. ]

我想把它转换成一个这样的树结构:

  1. [
  2. {
  3. id: 1,parent: null,children: [
  4. {
  5. id: 3,parent: 2
  6. },{
  7. id: 4,parent: 2
  8. }
  9. ]
  10. ]

我希望有一个可重用的功能,我可以随时调用任意列表.任何人知道一个很好的方法来处理这个?任何帮助或建议将不胜感激!

解决方法

  1. function treeify(list,idAttr,parentAttr,childrenAttr) {
  2. if (!idAttr) idAttr = 'id';
  3. if (!parentAttr) parentAttr = 'parent';
  4. if (!childrenAttr) childrenAttr = 'children';
  5.  
  6. var treeList = [];
  7. var lookup = {};
  8. list.forEach(function(obj) {
  9. lookup[obj[idAttr]] = obj;
  10. obj[childrenAttr] = [];
  11. });
  12. list.forEach(function(obj) {
  13. if (obj[parentAttr] != null) {
  14. lookup[obj[parentAttr]][childrenAttr].push(obj);
  15. } else {
  16. treeList.push(obj);
  17. }
  18. });
  19. return treeList;
  20. };

Fiddle

猜你在找的JavaScript相关文章