小编典典

如何将路径数组转换为JSON结构?

json

我发现了问题如何将文件路径转换为treeview?,但我不确定如何在JavaScript中获得所需的结果:

我正在尝试将路径数组转换为JSON树:

https://jsfiddle.net/tfkdagzv/16/

但是我的道路被覆盖了。

我正在尝试采取这样的事情:

[
    '/org/openbmc/path1', 
    '/org/openbmc/path2', 
    ...
]

…然后变成…

output = {
   org: {
     openbmc: {
       path1: {},
       path2: {}
     }
   }
}

我敢肯定这很容易,但是我缺少一些东西。


阅读 412

收藏
2020-07-27

共1个答案

小编典典

const data = [
“/org/openbmc/examples/path0/PythonObj”,
“/org/openbmc/UserManager/Group”,
“/org/openbmc/HostIpmi/1”,
“/org/openbmc/HostServices”,
“/org/openbmc/UserManager/Users”,
“/org/openbmc/records/events”,
“/org/openbmc/examples/path1/SDBusObj”,
“/org/openbmc/UserManager/User”,
“/org/openbmc/examples/path0/SDBusObj”,
“/org/openbmc/examples/path1/PythonObj”,
“/org/openbmc/UserManager/Groups”,
“/org/openbmc/NetworkManager/Interface”
];

const output = {};
let current;

for (const path of data) {
    current = output;

    for (const segment of path.split('/')) {
        if (segment !== '') {
            if (!(segment in current)) {
                current[segment] = {};
            }

            current = current[segment];
        }
    }
}

console.log(output);

您的解决方案很接近,只是没有current正确重置变量。用这个:

current = output;

代替这个:

current = output[path[0]];
2020-07-27