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.
Here is a solution I wrote:
It will do everything you need it to, and is compact. But, for the problem in your solution, it has to do with how you are managing
current
. Specifically, you had this:instead of this:
which meant that the code to initialize
output
, would run every time, becausepath[0]
is, in your data, always going to be''
, andoutput['']
doesn't yet exist, sooutput
would always be reset/overwritten.This function should do :
Demo
(see also this Fiddle)
NB: The resulting arrays need to be merged
This method works for both files & directories, and by using only arrays as the data format.
The structure is based upon arrays being folders, the first element being the folder name and the second - the contents array.
Files are just regular strings inside the array (but could easily be objects containing properties)
Converts =>
To =>
Script: