nubbbbbbb-_-bb nubbbbbbb-_-bb - 2 months ago 9
Javascript Question

Making recursive function

I'd like to make an object likes

obj = {2 : {3 : {4 : { } } } }

function tsttt (){
var tstObj = {};
var cntr = 0; //counter
var key = [2,3,4]; ///keys array what I want to 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 now empty object {}

Answer

It's returning the very last object you created, or the property assigned to "3". If you want it to return the full object then have it 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