skip to Main Content

I am trying to build a function that converts a list of paths into a object as below; the output of the script should be structured as below.

Output

data = [
{
    "type": "folder",
    "name": "dir1",
    "children": [
        {
            "type": "folder",
            "name": "photos",
            "children": [
                {
                    "type": "file",
                    "name": "mydir1.pdf",
                },
                {
                    "type": "file",
                    "name": "yourdir1.pdf",
                }
            ]
        }
    ]
}

And input is like this

paths = [
        "dir1/photos/mydir1.pdf",
        "dir1/photos/yourdir1.pdf"
    ]

2

Answers


  1. You can try below function:

    function buildTree(paths) {
      const tree = [];
      
      for (let path of paths) {
        const pathParts = path.split('/');
        let subtree = tree;
        
        for (let i = 0; i < pathParts.length; i++) {
          const part = pathParts[i];
          const isFolder = i < pathParts.length - 1;
          
          let node = subtree.find(n => n.name === part);
          
          if (!node) {
            node = {
              type: isFolder ? 'folder' : 'file',
              name: part,
              children: isFolder ? [] : undefined
            };
            
            subtree.push(node);
          }
          
          if (isFolder) {
            subtree = node.children;
          }
        }
      }
      
      return tree;
    }
    Login or Signup to reply.
  2. You can build tree with the help of object reference.

    const final = {result: []};
        
    for (const path of paths) {
      let context = final;
      
      for (const name of path.split("/")) {
        if (!context[name]) {
          context[name] = { result: [] };
          let type = "folder";
          if (name.endsWith(".pdf")) {
            type = "file";
          }
          context.result.push({name, type, children: context[name].result})
        }
        
        context = context[name];
      }
    }
    
    console.log(final.result)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search