Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Last active May 19, 2022 11:36
Show Gist options
  • Select an option

  • Save leonidkuznetsov18/e64826d95565fc6b8df47f5c773bb73d to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/e64826d95565fc6b8df47f5c773bb73d to your computer and use it in GitHub Desktop.
string to tree js
const paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc"];
const stringToTree = (data) => {
return data.reduce((r, path) => {
path.split('/').reduce((o, name) => {
var temp = (o.children = o.children || []).find(q => q.name === name);
if (!temp) o.children.push(temp = { name });
return temp;
}, r);
return r;
}, { children: [] });
}
console.log(stringToTree(paths));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment