遇到过这样一个题目
将嵌套的路由转成扁平化结构
嵌套路由代码
const testCase = [
{
path: '/jobs',
routes: [
{
path: '/auto_create',
},
{
path: '/:jobId',
routes: [{
path: '/info',
},
{
path: '/satisfaction',
routes: [{
path: ['/pandect/:candidateId', '/application/:applicationId', '/:id'],
}, ],
},
],
},
],
},
{
path: '/heat_preservation',
routes: [{
path: '/interview',
},
{
path: '/offer',
},
],
},
];
得到结果
[
'/jobs/auto_create',
'/jobs/:jobId/info',
'/jobs/:jobId/satisfaction/pandect/:candidateId',
'/jobs/:jobId/satisfaction/application/:applicationId',
'/jobs/:jobId/satisfaction/:id',
'/heat_preservation/interview',
'/heat_preservation/offer'
]
迭代加递归实现
const flat = (arr) => {
const res = []
const dfs = (arr, str) => {
arr.forEach(item => {
if(!item.routes) {
if(item.path instanceof Array) {
item.path.forEach(item => {
res.push(str+item)
})
return
}
return res.push(str+item.path)
}
else {
// 判断如果是数组继续递归遍历
dfs(item.routes, str+item.path)
}
})
}
dfs(arr, '')
console.log(res);
return res
}