【问题标题】:Split path into json nodes将路径拆分为 json 节点
【发布时间】:2020-05-23 07:56:13
【问题描述】:

在我的数据库中

|路径|id|

路径类似于

"Brand1/Cabinet/T18"
"Brand1/Cabinet/E12"
"Brand1/Cabinet"
"Brand1"
"Brand1/Uix"
"Brand2/Uix"
"Brand2/Asset/download"

如何拆分路径,使 json 看起来像具有根节点和子节点的树结构?

我想我必须用“/”分割路径。然后用节点创建一个数组。有没有更好更快的方法将这样的结构引入 json 节点?

【问题讨论】:

标签: javascript arrays json


【解决方案1】:

您可以使用Array.reduce 从这些路径构建一棵树。

我们首先遍历每条路径,然后将每条路径拆分为其组件。然后我们reduce这些组件来创建每个对象。

const paths = [
    "Brand1/Cabinet/T18",
    "Brand1/Cabinet/E12",
    "Brand1/Cabinet",
    "Brand1",
    "Brand1/Uix",
    "Brand2/Uix",
    "Brand2/Asset/download"
];

function createTree(paths, separator = "/") {
    return paths.reduce((obj, path) => {
        path.split(separator).reduce((acc, component) => { 
            return acc[component] = acc[component] || {};
        }, obj);
        return obj;  
    }, {});
}

console.log("Tree:", createTree(paths, "/"));

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多