我有一个如下所示的数据文件:
const website_settings = {
// 网站的设置的 menu 的数据
website_settings_menu_data: [
{
"name":"网站首页设置",
"icon":"settings",
"groups": [
{
"name": "网站首页",
"icon": "settings",
"children": [
.....
{
"name": "地图导航",
"route": "" // 跳转路径
},
{
"name": "页脚导航",
"route": "" // 跳转路径
}
]
}
]
},
{
"name":"网站新闻页设置",
"icon":"settings",
"groups": [
{
"name": "网站新闻页设置",
"icon": "settings",
"children": [
{
"name": "网站新闻页设置",
"route": "" // 跳转路径
}
......
]
}
]
},
{
"name":"实体服务器页面设置",
"icon":"settings",
"groups": [
{
"name": "实体服务器页面设置",
"icon": "settings",
"children": [
{
"name": "实体服务器页面设置",
"route": "" // 跳转路径
}
]
}
]
},
{
"name":"通知公告设置",
"icon":"settings",
"groups": [
{
"name": "公告设置",
"icon": "settings",
"children": [
{
"name": "notice-settings",
"route": "abc" // 跳转路径
}
]
}
]
}
]
}
export default website_settings;
如果有一个name
的要求,比如notice-settings
,我想查询出相关的route
,在示例中应该有 abc
(最后一个)。
在我的想法中,我可以使用双for循环来查询匹配的name
,但我不确定是否有更好的方法来存档,你可以看看在这?
最佳答案
您可以构建一个 Map 一次,因此每次查找都是 O(1):
const routes = new Map;
function check(array) {
for(const { name, groups, children, route } of array) {
if(children) check(children);
if(groups) check(groups);
if(name && route) routes.set(name, route);
}
}
check(website_settings_menu_data)
所以现在很简单:
routes.get("notice-settings") // "abc"
关于javascript - 有没有更好的方法来查询出双for循环的数据替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49426552/