2014-12-03 77 views
0

我有一个包含子字段的“页面”对象列表。这个子字段引用列表中的另一个对象。我想根据这个字段从这个列表创建一个树形层次结构。 我已经找到了解决办法here,但如果我有一个父field.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', 
    } 
    } 
] 
] 

我希望可以随时调用任意列表的可重用函数。任何人都知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!

回答

0

使用Underscore.js添加父母,然后用this solution

_.each(flat, function (o) { 
    o.child.forEach(function (childId) { 
    _.findWhere(flat, {id: childId}).parent = o.id; 
    }); 
}); 
0

下面这个函数建立一棵树从对象的列表中找到一个解决方案。 这对任何格式都不严格。 与您的示例唯一区别在于您提供了parent密钥,而不是child

function buildTree(flatList, idFieldName, parentKeyFieldName, fieldNameForChildren) { 
    var rootElements = []; 
    var lookup = {}; 

    flatList.forEach(function (flatItem) { 
     var itemId = flatItem[idFieldName]; 
     lookup[itemId] = flatItem; 
     flatItem[fieldNameForChildren] = []; 
    }); 

    flatList.forEach(function (flatItem) { 
     var parentKey = flatItem[parentKeyFieldName]; 
     if (parentKey != null) { 
     var parentObject = lookup[flatItem[parentKeyFieldName]]; 
     if(parentObject){ 
      parentObject[fieldNameForChildren].push(flatItem); 
     }else{ 
      rootElements.push(flatItem); 
     } 
     } else { 
     rootElements.push(flatItem); 
     } 

    }); 

    return rootElements; 
    } 

Here is a fiddle使用您的示例作为输入。

原始来源comes from this answer