微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从路由数组动态创建导航菜单 JSON

如何解决如何从路由数组动态创建导航菜单 JSON

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

输入

[
    "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",{
                "name": "Webstrom",{
                "name": "Photoshop",{
                "name": "firefox","children": []
            }
        ]
    },{
        "name": "Documents","children": [
            {
                "name": "Material-UI","children": [
                    {
                        "name": "src","children": [
                            {
                                "name": "index.js","children": []
                            },{
                                "name": "tree-view.js","children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

解决方法

你可以试试这个方法:

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。