遍历标准化数据的最佳方法是什么?

时间:2018-10-12 23:12:10

标签: javascript

我正在尝试遍历文件夹结构的一些规范化数据,但在实现过程中遇到了一些麻烦。

例如,我的数据如下所示:

dict: { 
    parent_folder: {files: [], folders: [folder1, folder2, folder3]},
    folder1: {files: [file1], folders: [folder4, folder 5]},
    folder2: {files: [file2], folders: []},
    folder3: {files: [], folders: [folder6]},
    folder4: {files: [file3, file4], folders: []},
    folder5: {files: [file5], folders: []},
    folder6: {files: [file6], folders: []}
}

基本上看起来像这样:

Root
    -Folder1/
        -file1
        -Folder4/
             -file3
             -file4
        -Folder5/
             -file5
    -Folder2/
        -file2
    -Folder3/
        -Folder6/
             -file6

现在我想基本遍历所有内容以将路径打印到每个文件

Root/Folder1/file1
Root/Folder1/Folder4/file3
Root/Folder1/Folder4/file4
Root/Folder2/file2
Root/Folder3/Folder6/file6

我似乎想不出一种遍历此归一化数据的简单方法,但我将不胜感激!

1 个答案:

答案 0 :(得分:2)

退后一步,考虑一个简单的函数,该函数接受这些对象之一并返回文件数组。那只是一个简单的map(),它添加了一些路径前缀,例如:

obj.files.map(f => prefix+f)

因此,如果编写针对特定对象执行此操作的函数,然后对几乎所有需要的文件夹调用相同的函数。您只需要在向下移动树时更改前缀:

let dict=  { 
    parent_folder: {files: [], folders: ['folder1', 'folder2', 'folder3']},
    folder1: {files: ['file1'], folders: ['folder4', 'folder5']},
    folder2: {files: ['file2'], folders: []},
    folder3: {files: [], folders: ['folder6']},
    folder4: {files: ['file3', 'file4'], folders: []},
    folder5: {files: ['file5'], folders: []},
    folder6: {files: ['file6'], folders: []}
}

function getFiles(obj, prefix="root/"){
    let r = obj.files.map(f => prefix+f)                     // get this level's files
    obj.folders.forEach(folder =>{                           // for the folders call the same thing
        r.push(...getFiles(dict[folder], prefix+folder+'/')) // alter the prefix as you go
    })
    return r

}
console.log(getFiles(dict.parent_folder))  // give it the parent to start