recursion - Recursive nested property creation in JavaScript -


i trying recursively build object tree of properties based on mongodb-ish selector "top.middle.bottom". there underscorejs helpers well:

function setnestedpropertyvalue(obj, fields, val) {   if (fields.indexof(".") === -1) {      // on last property, set value     obj[fields] = val;      return obj; // recurse   } else {     var onelevelless = _.first(fields.split("."));     var remaininglevels = _.rest(fields.split(".")).join(".");     // there more property levels remaining, set sub recursive call     obj[onelevelless] = setnestedpropertyvalue( {}, remaininglevels, val);   } }  setnestedpropertyvalue({}, "grandpaprop.papaprop.babyprop", 1); 

desired:

{    grandpaprop: {     papaprop: {       babyprop: 1     }   } } 

outcome:

undefined 

helps , hints appreciated.

instead of recursion choose iterative solution:

function setnestedpropertyvalue(obj, fields, val) {   fields = fields.split('.');    var cur = obj,   last = fields.pop();    fields.foreach(function(field) {       cur[field] = {};       cur = cur[field];   });    cur[last] = val;    return obj; }  setnestedpropertyvalue({}, "grandpaprop.papaprop.babyprop", 1); 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -