如何从路由数组动态创建导航菜单 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)