javascript - traverse through Parent-Child objects and construct path value using underscore.js -


i have object below

var childitems = function(child) {     return {         id: item.id,         type: child.type,         path: child.title,         parent: child.parent,         haschildren: true | false (based on condition)     }; }; 

also, have function returns child elements based on 'haschildren' , 'parent' attributes above object structure again returns data in childitems format. basically, if haschildren true level has 'n' childs within it.

can underscore.js can deep watch or using _.map can path values starting parent object child elements?

finally outcome of path required is.
parent/child1/child11/child111
parent/child1/child12/child112
(child1 in above example has 2 child elements child11 , child12)
parent/child2/child22/child222
parent/child2/child22/child333
(child22 in above example has 2 child elements child222and child333)

i'm using function this, construct paths keys recursively. hope helps

var getkeysflat = function(obj) {   /* helper function keys of object recursively,      e. g {foo: 42, bar {foo: 42}} have following keys:      ['foo', 'bar/foo']    */   var result = [];   var recurse = function (obj, keyprefix) {     if (keyprefix !== ''){       keyprefix = keyprefix + '/';     }     _.each(obj, function (val, key){       if (_.isobject(val)){         recurse(val, keyprefix + key);       } else {         result.push(keyprefix + key);       }     });   };   recurse(obj, '');   return result; };  console.log(getkeysflat({   value: 2,    child1: {     child11: 3   },   child2: {     child22: {       child222: 4     }   } })); 

Comments