鍍金池/ 問(wèn)答/HTML/ 請(qǐng)教大家一個(gè)js遞歸遍歷處理數(shù)組的問(wèn)題,謝謝啦!

請(qǐng)教大家一個(gè)js遞歸遍歷處理數(shù)組的問(wèn)題,謝謝啦!

//有如下數(shù)組,里面包含路由數(shù)據(jù)
const routes = [

{
    path:'/a',
    children:[
        {
            path:'a-1',
            children:[
                {
                       path:'a-1-1',
                       children:[]
                },
                {
                       path:'a-1-2',
                       children:[]
                },
                {
                       path:'a-1-3',
                       children:[]
                },
            ]
        },
        {
            path:'a-2',
            children:[
                {
                    path:'a-2-1'
                }
            ]
        }
    ]
},
{
    path:'/b',
    children:[
        {
            path:'b-1'
        },
        {
            path:'b-2'
        }
    ]
}

]

//想處理后能輸出
//[
// "/a/a-1/a-1-1",
// "/a/a-1/a-1-2",
// "/a/a-1/a-1-3",
// "/a/a-2/a-2-1",
// "/b/b-1",
// "/b/b-2"
// ]

//以下代碼只能輸出
//["/a/a-1/a-1-1,a-1-2,a-1-3,a-2/a-2-1", "/b/b-1,b-2"]

function gen(menu){

let tmp=[]
for(item of menu){
    if(item.children && item.children.length>0){
        tmp.push(item.path+'/'+gen(item.children))
    }else{
        tmp.push(item.path)
    }
}
return tmp

}

let m=gen(routes)
console.log(m)

回答
編輯回答
老梗
var walker = (path, route) => (route.children || []).length === 0 ?
        `${path}/${route.path}` :
        route.children.map(c => walker(`${path}/${route.path}`, c))

routes.map(r => walker('', r))
    .join('.').replace(/,/g, '.').split('.')
    .map(r => r.substring(1, r.length))

//?["/a/a-1/a-1-1", "/a/a-1/a-1-2", "/a/a-1/a-1-3", "/a/a-2/a-2-1", "/b/b-1", "/b/b-2"]
2017年9月17日 18:09
編輯回答
命于你
function routesPath(obj) {
    var pathlist = [];

    function f(o, p) {
        for(var i=0;i<o.length;i++) {
            if(!o[i].children || o[i].children.length === 0) {
                pathlist.push(p + o[i].path);
            } else {
                f(o[i].children, p + o[i].path + '/');
            }
        }
    }
    f(obj, '');
    return pathlist;
}

都是遞歸的各種考察,不過(guò)遞歸有個(gè)弊端,就是超過(guò)20多個(gè)層級(jí),瀏覽器就掛了,性能不是最優(yōu)的,最終還是要轉(zhuǎn)換成循環(huán)優(yōu)化

2017年1月27日 00:14