Javascript Array in Array 转 树结构

zpqsunny
  • 37

有一组数据

[
      [
         path1,
         path2,
         file1.txt
      ],
      [
         path1,
         file2.txt
      ],
      [
         file3.txt
      ]
]

想转成树结构

[
   {
     name: path1,
     children: [
        name: path2,
        children: [
            name: file1.txt
        ]
     ]
   },
   {
     name: path1,
     children: [
        name: file2.txt
     ]
   },
   {
     name: file3.txt
   }

]

求js 写法

回复
阅读 276
2 个回答

按顺序来构造树形的。

let list = [
    [
        'path1',
        'path2',
        'file1.txt'
    ],
    [
        'path1',
        'file2.txt'
    ],
    [
        'file3.txt'
    ]
];
let arrToTree = (paths)=>Object.assign({name:paths.shift()},paths.length ?{children:[arrToTree(paths)]} : {});

list.map(paths=>arrToTree(paths));

结果

[{"name":"path1","children":[{"name":"path2","children":[{"name":"file1.txt"}]}]},{"name":"path1","children":[{"name":"file2.txt"}]},{"name":"file3.txt"}]
var list = [
    [
        'path1',
        'path2',
        'file1.txt'
    ],
    [
        'path1',
        'file2.txt'
    ],
    [
        'file3.txt'
    ]
];
function transform(arr) {
    var ret = [];
    for (var i = 0; i < arr.length; ++i) {
        var _arr = arr[i];
        var obj = {}, _obj = obj;
        for (var j = 0; j < _arr.length; ++j) {
            var path = _obj.name = _arr[j];
            if (path.indexOf(".") < 0) {
                _obj = _obj.children = {};
            }
        }
        ret.push(obj);
    }
    return ret;
}
console.dir(transform(list));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏