【问题标题】:How to create Navigation Menu JSON dynamically from array of routes [closed]如何从路由数组动态创建导航菜单 JSON [关闭]
【发布时间】:2021-09-16 09:42:24
【问题描述】:

需要以下给定输出格式的输入。我该如何为此使用蛮力方法和动态编程方法?我试过了,但不知道如何继续。

输入

[
    "Application/Calendar",
    "Application/Chrome",
    "Application/Webstrom",
    "Application/Photoshop",
    "Application/firefox",
    "Documents/Material-UI/src/index.js",
    "Documents/Material-UI/src/tree-view.js"
]

输出

[
    {
        "name": "Application",
        "children": [
            {
                "name": "Calendar",
                "children": []
            },
            {
                "name": "Chrome",
                "children": []
            },
            {
                "name": "Webstrom",
                "children": []
            },
            {
                "name": "Photoshop",
                "children": []
            },
            {
                "name": "firefox",
                "children": []
            }
        ]
    },
    {
        "name": "Documents",
        "children": [
            {
                "name": "Material-UI",
                "children": [
                    {
                        "name": "src",
                        "children": [
                            {
                                "name": "index.js",
                                "children": []
                            },
                            {
                                "name": "tree-view.js",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

【问题讨论】:

标签: recursion dynamic-programming backtracking


【解决方案1】:

你可以试试这个方法:

let category = [
    "Application/Calendar",
    "Application/Chrome",
    "Application/Webstrom",
    "Application/Photoshop",
    "Application/firefox",
    "Documents/Material-UI/src/index.js",
    "Documents/Material-UI/src/tree-view.js"
].map(str => str.split("/"));

let result = [];
for (const names of category) names.reduce((children, name) => {
    let next = children.find(item => item.name == name);
    if (!next) children.push(next = { name, children: [] })
    return next.children;
}, result)
console.log(result)

【讨论】:

  • 嗨 Nur,感谢您的快速回复。是的,我尝试过但无法获得解决方案,而且我绝不打算不尝试就获得解决方案。即使在发布问题后,我也得到了回复,但与您的解决方案相比,这是无用的。您的解决方案令人印象深刻。谢谢!
  • 它回答你的问题了吗??
  • 嘿Nur,当然,它做到了。您的解决方案按预期工作。
  • @VivekSingh:我认为 Nur 是在暗示你可以接受这个答案。要“接受”,请单击答案旁边的勾号/复选标记。这不是强制性的,但鼓励这样做。这是感谢帮助过你的人的好方法,它表明答案对未来的读者有帮助。
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多