Saturday, 26 May 2018

How to create a nested object given an array of keys

Given is an array like this:

var level = ["a", "b", "x"];

The output should be:

{
    "a": {
        "b": {
            "x": {
            }
        }
    }
}

I tried this:

var level = ["a", "b", "x"];
var o = {};
for (var c = 0, len = level.length; c < len; c +=1 ) { 
    var part = level[c]; 
    o[part] = {}; // how to remember the last part?
}

How can I remember the last part and add the next level?



from How to create a nested object given an array of keys

No comments:

Post a Comment