javascriptmapschainable

Creating nested JS maps dynamically via a loop


The following code creates a nested JS map. It works already:

let a = data[0];
let b = data[1];
let c = data[2];
    
myMap.set(a, myMap.get(b) || new Map());
myMap.get(a).set(b, myMap.get(a).get(b) || new Map());
myMap.get(a).get(b).set(c, myMap.get(a).get(b).get(c) || new Map());
    

There can be many more variables than just a, b, c ... I'm wondering if there is a possibility to do the same via a loop (or another more tiny code)

I think a solution may be to create the method chains myMap.get(a).get(b).get(c) ... dynamically But I'm not sure wether this is possible, since eval is not a good solution.


Solution

  • Not sure if I understand your exact requirement, but you can do something like this

    const getNestedMap = (variables) => {
        const map = new Map();
        let temp = map;
        variables.forEach((variable) => {
            if (!temp.has(variable)) {
                temp.set(variable, new Map())
            }
    
            temp = temp.get(variable)
        })
    
        return map
    };
    

    And then call the function with an array of required variables

    getNestedMap([a, b, c]);