javascript - 递归访问对象中对象的键/值对并将它们组合成一个平面数组
问题描述
我有一个包含我所有路线的对象数组。我需要访问所有对象的嵌套子属性及其属性并将它们组合在一起。
我的对象数组看起来类似于:
const routes = [
{
path: '/system-settings1',
name: 'global-settings1',
component: 'tabs1',
children: [
{
path: 'level2-accounting1',
name: 'local-settings1',
components: 'modals1',
children: [
{
path: 'level3-accounting1',
name: 'local-settings1',
components: 'modals1'
}
// more children deeply nested(or not)
]
},
{
path: 'level2-accounting1',
name: 'local-settings1',
components: 'modals1',
children: [
{
path: 'level3-accounting1',
name: 'local-settings1',
components: 'modals1'
}
// more children deeply nested(or not)
]
}
],
},
{
path: '/system-settings2',
name: 'global-settings2',
component: 'tabs2',
children: [
{
path: 'level2-accounting2',
name: 'local-settings2',
components: 'modals2',
children: [
{
path: 'level3-accounting2',
name: 'local-settings2',
components: 'modals2'
}
// more children deeply nested(or not)
]
},
{
path: 'level3-accounting2',
name: 'local-settings2',
components: 'modals2',
children: [
{
path: 'level4-accounting2',
name: 'local-settings2',
components: 'modals2'
}
// more children deeply nested(or not)
],
}
],
},
// more objects with similar key/value pairs
];
我需要将对象数组变成单级数组,如下所示:
[
{
path: '/system-settings1',
name: 'global-settings1',
component: 'tabs1',
},
{
path: 'level2-accounting2',
name: 'local-settings2',
components: 'modals2',
},
{
path: 'level3-accounting1',
name: 'local-settings1',
components: 'modals1'
},
{
path: 'level2-accounting1',
name: 'local-settings1',
components: 'modals1',
}
// so on if there is more objects etc
]
我曾尝试.map()
与循环.filter()
结合while
,但老实说,我缺乏自己完成的技能,不值得包括我的尝试。如果有人可以帮助我并解释这将不胜感激。
解决方案
我尝试编辑您的代码示例,以使它们有意义并且运行时没有错误。routes
这是一个在根数组以及任何嵌套数组上调用的递归函数children
:
const flatten = routes => {
const flattened = [];
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
//for each route, grab only the information about the route itself (no children)
const { path, name, components } = route;
const flatRoute = { path, name, components };
//add the new route object to our return array
flattened.push(flatRoute);
//if the route had children, recursively call flatten on them
//and add each child to our return array
if (route.children) {
const flatChildren = flatten(route.children);
flattened.push(...flatChildren);
}
}
return flattened;
};
推荐阅读
- ios - 如何正确调整 UITabBarController 图标的大小?
- javascript - 如何在 Node 中共享范围和变量?
- google-cloud-vision - 如何同时使用 Google Cloud Search 和 Vision API
- c++ - EXC_BAD_ACCESS (code=1, address=0x0) 当调用“glClear(GL_COLOR_BUFFER_BIT);” 在 glfw 的 hello world 程序中
- azure-cosmosdb - FeedResponse 是否包含来自单个逻辑分区的结果?
- json - 将 JSON 解析为 Access 表
- vba - 在 Outlook 中运行 VBA 宏时暂停/停止下载新电子邮件 [暂停/停止同步]
- c - 在 exec 函数中使用来自用户的字符串
- python - 显示 DataFrame 单元格的全部内容而不用省略号截断文本
- javascript - 为什么我的组件的这一部分会在间隔调用时重新呈现?