javascript - Making recursive function -
i'd make object likes
obj = {2 : {3 : {4 : { } } } }
function tsttt (){ var tstobj = {}; var cntr = 0; //counter var key = [2,3,4]; ///keys array want put in object function re(obj){ var k = key[cntr]; if(cntr == 2){ return obj; }else if(!(k in obj)){ obj[k] = {}; } cntr++; return re(obj[k]); } var rslt = re(tstobj); logger.log(rslt); //google apps script log }
it returns empty object {}
it's returning last object created, or property assigned "3". if want return full object have return tstobj.
function re(obj){ var k = key[cntr]; if(cntr == 2){ return tstobj; }else if(!(k in obj)){ obj[k] = {}; } cntr++; return re(obj[k]); }
Comments
Post a Comment