Javascript在树结构中排列数组

时间:2014-04-30 06:46:48

标签: javascript arrays tree hierarchy

我已按照此处的教程Model Tree Structure with An Array Of Ancestors 创建了类别层次结构。当我进行查询时,我得到的结果与以下数组转储相同。

[
    {id:1,name:'A', ancestors:[]}

        ,{id:2,name:'AA',parent:1, ancestors:[1]}

            ,{id:4,name:'AAA',parent:2, ancestors:[1,2]}
            ,{id:5,name:'AAB',parent:2, ancestors:[1,2]}

        ,{id:3,name:'AB',parent:1, ancestors:[1]}

            ,{id:6,name:'ABA',parent:3, ancestors:[1,3]}
            ,{id:7,name:'ABB',parent:3, ancestors:[1,3]}

    ,{id:8,name:'B', ancestors:[]}
]

请帮我动态转换上面的数组,如下所示:

[
    {id:1, name:'A', ancestors: [], children : [
        //children of A
        {id:2, name:'AA', parent:1, ancestors:[1], children:[
            //children of AA
            {id:4, name:'AAA', parent:2, ancestors:[1,2], children:[]}
            , {id:5, name:'AAB', parent:2, ancestors:[1,2], children:[]}

        ]}

        , {id:3, name:'AB', parent:1, ancestors:[1], children:[
            //children of AB
            {id:6, name:'ABA', parent:3, ancestors:[1,3], children:[]}
            , {id:7, name:'ABB', parent:3, ancestors:[1,3], children:[]}

        ]}

    ]}

    ,

    {id:8, name:'B', ancestors:[]}

到目前为止,我已经能够得到以下结果

[
    {id:1,name:'A', ancestors:[], children:[2,3]}

        ,{id:2,name:'AA',parent:1, ancestors:[1], children:[4,5]}

            ,{id:4,name:'AAA',parent:2, ancestors:[1,2], children:[]}
            ,{id:5,name:'AAB',parent:2, ancestors:[1,2], chldren:[]}

        ,{id:3,name:'AB',parent:1, ancestors:[1], children:[6,7]}

            ,{id:6,name:'ABA',parent:3, ancestors:[1,3], children:[]}
            ,{id:7,name:'ABB',parent:3, ancestors:[1,3], children:[]}

    ,{id:8,name:'B', ancestors:[], children:[]}
]

撰写此代码:

//var items = _GIVEN AT THE TOP_;

var indexedItem = items.map(function(item){
    return item.id;
});

items.forEach(function(item){
    if(!item.parent) {return;}

    var parent = items[indexedItem.indexOf(item.parent)];
    if(!parent.children){parent.children = [];}
    parent.children.push(item.id);
});

1 个答案:

答案 0 :(得分:0)

这是我使用递归的解决方案:

function findChildren(array, itemId){
    var newItems = []
    array.forEach(function(el,index){
        if(el.parent == itemId)
            {
                var itemsClone = JSON.parse(JSON.stringify(items));
                itemsClone.pop(index);
                el.children = findChildren(itemsClone, el.id);
                newItems.push(el);
            }


    });
    return newItems;
}


var tree = findChildren(items);