recursion - Underscore/Lodash - Object from parent/children -


i'm trying create formatted collection 1 database (mongo).

here's input's format :

[{_id:1,name:'1'},  {_id:2,name:'2},  {_id:3,name:'1-1',parent:1},  ...  {_id:50,name:'1-1-3',parent:3}] 

as can see, 'deepest ancestors' _ids 1 , 2. first node of children contains _id 3, has child, _id 50.

i'm struggling create kind of collection, using lodash :

[{     _id:1,name:'1',children:[         {_id:3,name:'1-1',children:[             ...,             {_id:50,name:'1-1-3',children:[]}         ]},         ...     ] },{     _id:1,name:'1',children:[...] }] 

here's i've tried :

var result=_.chain(input)     .groupby('parent')     .pairs()     .map(function(currentitem){         return _.object(_.zip(['parent','children'],currentitem))     })     .value(); 

but doesn't work in recursive way...

is able me ?

thanks.

you can iterate on collection required structure:

// create , indexed object _id field key - improve performance var indexed = _.indexby(data, '_id');  // iterate create structure _.each( data, function(datum){    datum.children = [];    if( _.has(datum,'parent')){       indexed[datum.parent].children.push(datum);     } }) 

this solution assume parent processed before each child i.e. children array created before it's pushed into. number of ways solve if needs above code shows way create nested structure.


Comments