简体   繁体   中英

Javascript Arrange Array in Tree Structure

I have created category hierarchy following a tutorial here Model Tree Structure with An Array Of Ancestors . When I do query, I am getting result which is identical to the following array dump.

[
    {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:[]}
]

Please help me dynamically transforming the above array to as below:

[
    {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:[]}

]

I have been able to yield the following result so far

[
    {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:[]}
]

By writing this code :

//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);
});

Here is my solution using recursion:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM