JavaScript:从json对象列表构建树状结构

时间:2017-03-23 20:48:10

标签: javascript json

我有一个JSON对象列表

var files = [{name:"1.xml", path:"folder1/1.xml", tag:"folder1", type:"file"},
{name:"2.jpg",      path:"folder1/folder2/2.jpg", type:"file", tag:"folder1/folder2"},
{name:"3.doc", path:"folder1/folder2/3.doc", type:"file", tag:"folder1/folder2"}];    

我需要创建以下结构

[
{
name:"folder1",
path:"folder1",
type:"folder",
items:[
    {name:"folder2", 
     path:"folder1/folder2", 
     type:"folder", 
     items:[
         {name:"2.xml",path:"folder1/folder2/2.xml", type="file"},
         {name:"3.xml",path:"folder1/folder2/3.xml", type="file"} 
      ]},
     {name:"1.xml", path:"folder1/1.xml", type="file"}
]}]

基本上,每个文件的tag属性必须成为一个文件夹,并将文件和其他标记分组到items集合中。

1 个答案:

答案 0 :(得分:0)

你可以使用这个递归函数:

function buildTree(files) {
    var result = { path: '', items: [] },
        i = 0;
    
    if (!files.length) return [];
    // Sort items so they get processed in folder order
    files.sort( (a, b) => a.path.localeCompare(b.path) );
    
    (function recurse(curr) {
        var tag = files[i].tag;
        tag.substr(curr.path.length+!!curr.path).split('/').forEach( folder => {
            var obj = {
                name: folder,
                path: (curr.path ? curr.path + '/' : '') + folder,
                type: 'folder',
                items: []
            };
            curr.items.push(obj);
            curr = obj;
        });
        while (i < files.length) {
            var file = files[i];
            if (file.tag.indexOf(tag + '/') === 0) {
                recurse(curr);
            } else if (file.tag === tag) {            
                curr.items.push({
                    name: file.name,
                    path: file.path,
                    type: 'file'
                });
                i++;
            } else {
                break;
            }
        }
    })(result);
    return result.items;
}

// Sample data
var files = [
{name:"1.xml", path:"folder1/1.xml",         type:"file", tag:"folder1"},
{name:"2.jpg", path:"folder1/folder2/2.jpg", type:"file", tag:"folder1/folder2"},
{name:"3.doc", path:"folder1/folder2/3.doc", type:"file", tag:"folder1/folder2"},
{name:"4.doc", path:"folder1/folder23/3.doc", type:"file", tag:"folder1/folder23"},
{name:"5.doc", path:"folder12/3.doc", type:"file", tag:"folder12"},
];

// transform to tree structure
var tree = buildTree(files);
// Output result
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }