Robin Mehra
Robin Mehra

Reputation: 161

file paths to json tree structure

I have data as following: `

[
  {path: "path1/path2/path3/index.file", title: "path3 Title"},
  {path: "path1/path2/index.file", title: "path2 Title"},
  {path: "path1/path2/path3/path4.file", title: "path4 Title"},
  {path: "path5/path5.file", title: "path5 Title"},
  {path: "path1/index.file", title: "path1 Title"},
  {path: "index.file", title: "path0 Title"},
]

` and i need something like :-

`

[
  {title: "path1 title", children: [
    {title: "path2 Title", children: [
      title: "path3 Title", children: [
        title: "path 4 Title", children: []
      ]
    ]
  ]},
  {
    title: "path 5 title", children: []
  },
  {
    title: "path 0 title", children: []
  }
]

`

so far i have written this but its not helping me at all. `

let treepath = {};
      paths.forEach(path => {
        let levels = path.split("/");
        let file = levels.pop();

        let prevLevel = treePath;
        let prevProp = levels.shift();

        levels.forEach(prop => {
          prevLevel[prevProp] = prevLevel[prevProp] || {};
          prevLevel = prevLevel[prevProp];
          prevProp = prop;
        });

        prevLevel[prevProp] = (prevLevel[prevProp] || []).concat([file]);
      });

    console.log('treepath', treePath);

`

There can be various paths. they are coming dynamically. i need to set them as children. i need to do this in Javascript code.Appreciate your help. Thanks.

Upvotes: 0

Views: 534

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386868

You could take a shadow tree and assign the title later to the the structure.

var data = [{ path: "path1/path2/path3/index.file", title: "path3 Title" }, { path: "path1/path2/index.file", title: "path2 Title" }, { path: "path1/path2/path3/path4.file", title: "path4 Title" }, { path: "path5/path5.file", title: "path5 Title" }, { path: "path1/index.file", title: "path1 Title" }, { path: "index.file", title: "path0 Title" }],
    tree = data
        .reduce((r, { path, title }) => {
            let directories = ('root/' + path).split('/');

            directories.pop();

            directories
                .reduce((d, key) => {
                    if (!d[key]) {
                        d[key] = { _: [] };
                        d._.push(d[key].parent = { title: null, children: d[key]._ });
                    }
                    return d[key];
                }, r)
                .parent
                .title = title;
            return r;
        }, { _: [] })
        ._;

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions