Maybe there is already a solution, but I can't find it. I try to access different slots in a multi dimensional array dynamical but with the challenge of different depths. Basically, it looks like this:
var source = [];
source['lvl1'] = [];
source['lvl1']['lvl2a'] = [];
source['lvl1']['lvl2a']['lvl3'] = "ping";
source['lvl1']['lvl2b'] = "pong";
If the depth is fix, I could write code like this:
var path1 = ["lvl1","lvl2a","lvl3"];
var path2 = ["lvl1","lvl2b"];
console.log(source[path1[0]][path1[1]][path[2]]); // => ping
console.log(source[path2[0]][path2[1]]); // => pong
My problem is to write a code that works for both variants. This would work:
switch(path.length)
{
case 1:
console.log(source[path[0]]);
break;
case 2:
console.log(source[path[0]][path[1]]);
break;
case 3:
console.log(source[path[0]][path[1]][path[2]]);
break;
}
But this is neither efficient nor elegant. Has somebody another solution that works for example with some kind of loop?!?
Thanks Thomas