将平面对象扩展为层次结构

时间:2019-02-13 12:58:54

标签: javascript

我正在寻找扩展这种扁平结构的最佳方法

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

进入此层次结构

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
    }]
  }
]

有什么想法吗?请。

1 个答案:

答案 0 :(得分:0)

方法不是很糟糕,它可以执行,但是有一种情况它无法处理 父节点不存在的情况(应创建),我已对此部分进行了评论。

缺少中间路径支持的更新版本

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));