function nestRoutes(flatRoutes) {
const nestedRoutes = [];
function findParent(route, parentPath) {
return flatRoutes.filter(flatRoute => flatRoute.parentPath === parentPath);
}
flatRoutes.forEach(route => {
if (!route.parentPath) {
route.children = findParent(route, route.path);
nestedRoutes.push(route);
}
});
return nestedRoutes;
}
const flattenedRoutes = [
{ path: '/', name: 'Home' },
{ path: '/dashboard', name: 'Dashboard', parentPath: '/' },
{ path: '/overview', name: 'Overview', parentPath: '/dashboard' },
{ path: '/analytics', name: 'Analytics', parentPath: '/dashboard' },
{ path: '/settings', name: 'Settings', parentPath: '/' },
{ path: '/about', name: 'About' }
];
const nestedRoutes = nestRoutes(flattenedRoutes);
console.log('原数组---------------------',flattenedRoutes);
console.log('转换后的数组---------------',nestedRoutes);
js将数组转换成多维数组
最新推荐文章于 2023-09-21 13:34:09 发布