Tim
Tim

Reputation: 2411

What is the best way to traverse through normalized data?

I'm attempting to traverse through some normalized data of a folder structure and I'm having some trouble with my implementation.

Say for example, my data looks something like this:

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

Basically this looks like this:

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

Now I want to basically traverse through everything to print the path to every single file

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

I can't seem to think of an easy way to traverse through this normalized data but I would appreciate any help!

Upvotes: 0

Views: 47

Answers (1)

Mark
Mark

Reputation: 92440

Take a step back and think about a simple function that takes one of these objects and returns an array of files. That's just a simple map() which adds some path prefix like:

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

So if you write a function that does that for a particular object, then calls the same function with all of the folders you almost have what you need. You just need to alter the prefix as you move down the tree:

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

Upvotes: 2

Related Questions