Create nested object from multiple string paths

I suggest implementing a tree insertion function whose arguments are an array of children and a path. It traverses the children according to the given path and inserts new children as necessary, avoiding duplicates:

// Insert path into directory tree structure:
function insert(children = [], [head, ...tail]) {
  let child = children.find(child => child.name === head);
  if (!child) children.push(child = {name: head, children: []});
  if (tail.length > 0) insert(child.children, tail);
  return children;
}

// Example:
let paths = [
  '/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'
];

let objectArray = paths
  .map(path => path.split('/').slice(1))
  .reduce((children, path) => insert(children, path), []);

console.log(objectArray);

Tags:

Javascript