简体   繁体   中英

Expand flat object into hierarchical structure

I'm trying to find best approach to expand this flat structure

var input = [  
   {  
      "path":"/",
      "size":1111
   },
    {  
      "path":"/test1",
      "size":2222
   },
   {  
      "path":"/test1/folder2",
      "size":3333
   },
   {  
      "path":"/test1/folder2",
      "size":4444
   },
   {  
      "path":"/test7/folder1",
      "size":5555
   }
]

into this hierarchical structure

var expectedoutput = [{
    "path": "/",
    "size": 1111
  },
  {
    "path": "/test1",
    "size": 2222,
    "items": [{
        "path": "/test1/folder2",
        "size": 3333,
      },
      {
        "path": "/test1/folder2",
        "size": 4444
      }
    ]
  },
  {
    "path": "/test7",
    "items": [{
      "path": "/test7/folder1",
      "size": 5555
    }]
  }
]

Any ideas? please.

Not so bad approach, it work's but there is one scenario which it cannot handle Scenario when parent node doesn't exists (should be created) i've commented this part.

Updated version with missing intermediate paths support

function expand_object(list) {
    var map = {}, node, roots = [], i;
    for (i = 0; i < list.length; i += 1) {
        map[list[i].path] = i; // map  
        list[i].items = []; // place for children
    }
    for (i = 0; i < list.length; i += 1) {
        node = list[i];

        //find parent, example  "path":"test1/folder2"  parent= "test1"
        var lastSlash = node.path.lastIndexOf('/');
        if (lastSlash > 1) {
            lastSlash = lastSlash == -1 ? node.path.length : lastSlash;
            parentNode = node.path.substring(0, lastSlash);
        }
        else {
            parentNode = "/";
        }

        if (parentNode !== "/") {
            // creat missing nodes
            if (!list[map[parentNode]]) {

                list.push({ "name": parentNode ,"path": parentNode, "items": [] })
                map[list[list.length-1].path] = list.length-1;
            }

            var c = list[map[parentNode]];
            list[map[parentNode]].items.push(node);


        } else {
            roots.push(node);
        }
    }
    return roots;
}
var input = [  
   {  
      "path":"/",
      "size":1111
   },
      {  
      "path":"/",
      "size":2222
   },
    {  
      "path":"/test1",
      "size":2222
   },
   {  
      "path":"/test1/folder2",
      "size":3333
   },
   {  
      "path":"/test1/folder2",
      "size":4444
   }

 ,
    { //Missing node
       "path":"/test7/folder1",
       "size":5555
    }
]
console.log(expand_object(input));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM