Last active
May 19, 2022 11:36
-
-
Save leonidkuznetsov18/e64826d95565fc6b8df47f5c773bb73d to your computer and use it in GitHub Desktop.
string to tree js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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