【发布时间】:2020-03-30 18:49:19
【问题描述】:
我有 objects 的 array 和那些 objects 包含一个名为 children 的属性,它们也是 objects 并且他们会在多个层次上重复它们(或不重复)。
基本上,我需要完成两件事:
获取第一级
path属性的值及其在children属性中的多个级别。将它们连接在一起得到单个
string,这将是一个路由/URL。
例如,按照下面的示例代码,我需要像这样获取三个不同的 URL/路由:
/system-settings1/accounting1/accounting1/etc
/system-settings2/accounting2/accounting2/etc
/system-settings3/accounting3/accounting3/etc
这是我的object的小样本:
const routes = [
{
path: '/system-settings1',
name: 'global-settings1',
component: 'tabs1',
children: {
path: 'accounting1',
name: 'local-settings1',
components: 'modals1',
children: {
path: 'accounting1',
name: 'local-settings1',
components: 'modals1'
// more children deeply nested(or not)
}
}
},
{
path: '/system-settings2',
name: 'global-settings2',
component: 'tabs2',
children: {
path: 'accounting2',
name: 'local-settings2',
components: 'modals2',
children: {
path: 'accounting1',
name: 'local-settings1',
components: 'modals1'
// more children deeply nested(or not)
}
}
},
{
path: '/system-settings3',
name: 'global-settings3',
component: 'tabs3',
children: {
path: 'accounting3',
name: 'local-settings3',
components: 'modals3',
children: {
path: 'accounting1',
name: 'local-settings1',
components: 'modals1'
// more children deeply nested(or not)
}
}
},
]
我能够像这样获得父路径及其下一个直接子路径:
const routeParentPaths = routes.map(({path}) => path);
const routeChildrenPaths = routes.map(({children}) => children.path);
console.log((routeParentPaths.concat(routeChildrenPaths)));
但我需要找到一种方法来访问其所有子路径,而且我需要找到一种连接方法,以便为每个 object 形成一个正确的 URL。
您会找到一个代码示例here。
【问题讨论】:
-
我借此机会宣传我的用于定义路由的小型库:npmjs.com/package/@syndicode/route-maker PS,目前尚不清楚路径数组以及您为什么想要
-
感谢您在这里感谢人们!但是,这不是必需的,并且不鼓励在帖子中使用,因为首选技术写作。通常最好只是默默地接受/赞成/反对。
标签: javascript arrays object url routes