0

In my database I have

|path|id|

The path is something like

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

How I can split the path so the json will looks like a tree structure with root and child nodes?

I think I have to split the path with "/". Then create an array with the nodes. Is there a better an faster way to bring a structure like this into json nodes?

ingo
  • 776
  • 1
  • 10
  • 25
  • You could also look at [this question](https://stackoverflow.com/questions/44168616/build-nested-json-from-string-of-nested-keys) that has the same idea behind. – Noah Boegli Feb 07 '20 at 08:05

1 Answers1

0

You can use Array.reduce to build a tree from these paths.

We start by iterating over each path, then splitting each path into its components. We then reduce these components to create each object.

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, "/"));
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40