Home > Mobile >  Merge arbitrary amount of arrays, which may have shared elements, into a single, nested dictionary o
Merge arbitrary amount of arrays, which may have shared elements, into a single, nested dictionary o

Time:10-23

I'm attempting to compile a big-picture "folder structure" dictionary object from multiple arrays that each contain folder name strings. Some of the folder/sub-folder names will be shared between the arrays and the nested dictionary object needs to reflect that.

When looping through each array of folder names to check if that "structure" already exists within the nested dictionary object, I can't seem to figure out how to account for previous folders and shared folders, considering there could be any number of folders in each array. How can you account for that arbitrary number without manually writing an endless amount of for-loops?

Here's a basic example of what the arrays could look like:

    var test1 = ["sub1", "sub2", "sub3"];
    var test2 = ["sub1", "other"];
    var test3 = ["sub0", "misc"];
    var test4 = ["sub1", "sub2", "proj", "img"];

And here's the desired output based on the above example:

    var folder_structure = {
        "sub0": {
            "misc": {}
        },
        "sub1": {
            "sub2": {
                "sub3": {},
                "proj": {
                    "img": {}
                }
            },
            "other": {}
        },
    };

CodePudding user response:

Well, you can do that in many ways. Here's my solution based on recursion:

var test1 = ["sub1", "sub2", "sub3"];
var test2 = ["sub1", "other"];
var test3 = ["sub0", "misc"];
var test4 = ["sub1", "sub2", "proj", "img"];
const arrys = [test1, test2, test3, test4]; // just organizing all together

const addFolders = (root, folders) => {

    // let the base case for recursion be an empty folders array
    if (!folders.length) return root;

    const curFolderName = folders[0];
    const newFolder = root[curFolderName] || {};
    root[curFolderName] = newFolder;
    
    // recursive call:
    return addFolders(root[curFolderName], folders.slice(1));
}

// here you can also use an empty object as temp 
// result-storage and a simple for or forEach loop 
// instead of reduce method (up to your taste). 
const result = arrys.reduce((acc, folders) => addFolders(acc, folders) && acc, {}) 

console.dir(result);
  • Related