Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - How to convert an array of paths into JSON structure?

I found the question How to convert a file path into treeview?, but I'm not sure how to get the desired result in JavaScript:

I'm trying to turn an array of paths into a JSON tree:

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

But my path is being overwritten.

I'm trying to take something like this:

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

... and turn it into...

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

I'm sure this is pretty easy, but I'm missing something.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);

Your solution was close, you just didn't reset the current variable properly. Use this:

current = output;

instead of this:

current = output[path[0]];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...