I came across a query on how to convert a file path into a treeview, and I'm uncertain about achieving the desired outcome using JavaScript:
My goal is to transform an array of paths into a JSON tree structure:
var paths = [
"/org/openbmc/UserManager/Group",
"/org/stackExchange/StackOverflow",
"/org/stackExchange/StackOverflow/Meta",
"/org/stackExchange/Programmers",
"/org/stackExchange/Philosophy",
"/org/stackExchange/Religion/Christianity",
"/org/openbmc/records/events",
"/org/stackExchange/Religion/Hinduism",
"/org/openbmc/HostServices",
"/org/openbmc/UserManager/Users",
"/org/openbmc/records/transactions",
"/org/stackExchange/Religion/Islam",
"/org/openbmc/UserManager/Groups",
"/org/openbmc/NetworkManager/Interface"
];
The expected JSON structure based on the folder paths should look like this:
var xyz = [{
"path": "photos",
"name": "photos",
"children": [
{
"path": "photos/summer",
"name": "summer",
"children": [
{
"path": "photos/summer/june",
"name": "june",
"children": [
{
"path": "photos/summer/june/windsurf",
"name": "windsurf",
}
]
}
]
},
{
"path": "photos/winter",
"name": "winter",
"children": [
{
"path": "photos/winter/january",
"name": "january",
"children": [
{
"path": "photos/winter/january/ski",
"name": "ski",
},
{
"path": "photos/winter/january/snowboard",
"name": "snowboard",
}
]
}
]
}
]
}];
I attempted to use the following function, but it's not yielding the desired results:
var parsePathArray = function(paths) {
var parsed = [];
for (var i = 0; i < paths.length; i++) {
var position = parsed;
var split = paths[i].split('/');
for (var j = 0; j < split.length; j++) {
if (split[j] !== "") {
if (typeof position[split[j]] === 'undefined')
position[split[j]] = {};
position.children = [position[split[j]]];
position.name = split[j];
position = position[split[j]];
}
}
}
return parsed;
}