Loop over each line and allow it to object:
var glob={name:undefined,children:[]}; ["/root/library/Folder 1","/root/library/Folder 2","/root/library/Folder 1/Document.docx","/root/library/Folder 1/Document 2.docx","/root/library/Folder 2/Document 3.docx","/root/library/Document 4.docx"] .forEach(function(path){ path.split("/").slice(1).reduce(function(dir,sub){ var children; if(children=dir.children.find(el=>el.name===sub)){ return children; } children={name:sub,children:[]}; dir.children.push(children); return children; },glob); }); console.log(glob);
http://jsbin.com/yusopiguci/edit?console
Enhanced Version:
var glob={name:undefined,children:[]}; var symbol="/" ; var lookup={[symbol]:glob}; ["/root/library/Folder 1","/root/library/Folder 2","/root/library/Folder 1/Document.docx","/root/library/Folder 1/Document 2.docx","/root/library/Folder 2/Document 3.docx","/root/library/Document 4.docx"] .forEach(function(path){ path.split("/").slice(1).reduce(function(dir,sub){ if(!dir[sub]){ let subObj={name:sub,children:[]}; dir[symbol].children.push(subObj); return dir[sub]={[symbol]:subObj}; } return dir[sub]; },lookup); }); console.log(glob);
It produces the same result, but can be much faster (to O (n) vs O (n + n!)) Http://jsbin.com/xumazinesa/edit?console
source share