Making recursive function with 2 pram

Question!

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 {}



Answers
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]);
  }


This video can help you solving your question :)
By: admin