Last active
July 1, 2016 19:17
-
-
Save joaovarandas/0294c6496a24ca217ba0284556984726 to your computer and use it in GitHub Desktop.
Translate a list of slash-paths to a Tree in JavaScript
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
var input = [ | |
{ "name": "File 1", "path": "Home/Folder A/Folder A-B" }, | |
{ "name": "File 2", "path": "Home/Folder C/Folder C-A/File 4.hist" }, | |
{ "name": "File 3", "path": "Home/Folder A/Folder A-B" }, | |
{ "name": "File 4", "path": "Home/Folder C/Folder C-A" }, | |
{ "name": "File 5", "path": "Home/Folder B" }, | |
{ "name": "File 6", "path": "Home/Folder C/Folder C-A/File 4.hist" }, | |
{ "name": "File 7", "path": "Home/Folder B/Folder B-B" }, | |
{ "name": "File 8", "path": "Home/Folder C/Folder C-A/File 4.hist" }, | |
{ "name": "File 9", "path": "Home/Folder B" }, | |
{ "name": "File 10", "path": "Home/Folder C/Folder C-B" }, | |
{ "name": "File 11", "path": "Home/Folder A" }, | |
{ "name": "File 12", "path": "Home" } | |
]; | |
function translatePath(input, pathAttrName) { | |
var o = []; | |
for (var i = 0; i < input.length; i++) { | |
var chain = input[i][pathAttrName].split("/"); | |
var cn = o; | |
for (var j = 0; j < chain.length; j++) { | |
var wn = chain[j]; | |
var ln = cn; | |
for (var k = 0; k < cn.length; k++) { | |
if (cn[k].name == wn) { | |
cn = cn[k].children; | |
break; | |
} | |
} | |
if (ln == cn) { | |
var nn = cn[k] = { name: wn, children: []}; | |
cn = nn.children; | |
} | |
} | |
cn.push(input[i]); | |
} | |
return o; | |
} | |
print(JSON.stringify(translatePath(input, "path"), null, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment