我们将路由配置存储在node_modules
当我们将其全部分组到应用程序中的一个数组中时,我们希望根据path
对其进行正确排序。
对于childRoutes
可识别的孩子,我们希望保留深度。
它是这样的:
const routeConfig1 = [
{
path: "/user-management",
childRoutes: [
{
path: "/user-management/user",
childRoutes: [
{
path: "/user-management/user/service"
}
]
}
]
}
];
const routeConfig2 = [
{
path: "/user-management",
childRoutes: [
{
path: "/user-management/user",
component: "UserComponent",
childRoutes: [
{
path: "/user-management/user/service/tokyo",
component: "TokyoService"
}
]
}
]
}
];
const routeConfig3 = [
{
path: "/user-management",
childRoutes: [
{
path: "/user-management/user/:id"
}
]
}
];
const routeConfigList = [routeConfig1, routeConfig2, routeConfig3];
function mergeRouteConfig(list) {
let newList = [...list];
list.map(r => {});
return newList;
}
const flatten = mergeRouteConfig(routeConfigList);
const expected = [
[
{
path: "/user-management",
childRoutes: [
{
path: "/user-management/user",
component: "UserComponent",
childRoutes: [
{
path: "/user-management/user/service"
},
{
path: "/user-management/user/service/tokyo",
component: "TokyoService"
}
]
},
{
path: "/user-management/user/:id"
}
]
}
]
];
const flattenStr = JSON.stringify(flatten, null, 2);
const expectedStr = JSON.stringify(expected, null, 2);
const result = flattenStr === expectedStr;
document.getElementById(
"app"
).innerHTML = `<h2>Result: ${`<span style="color: ${
result ? "green" : "red"
}">${result ? "OK" : "NOK"}</span>`}</h2>
<pre>
${flattenStr}
</pre>
<h2>Expected</h2>
<pre>
${expectedStr}
</pre>
`;
body{font-family:sans-serif}pre{background:#ccc}
<div id="app"></div>
代码和框:https://codesandbox.io/s/1zmy69r5mq
我尝试过使用Map
,reduce
,但是我的代码看起来有些复杂,如何正确实现呢?