javascript - JSON and recursion -


sorry, i'm newbie , it's been awhile since i've touched recursion, apologize if question may seem little basic. have json structure this:

  {    "id": "1111",    "name": "outdoor skiing",    "parent_id": "1110",    "parents": [      {         "id": "1000000",         "name": "movies"      },      {         "id": "1000001",         "name": "outdoor movies"      }    ]  } 

and want flip in structure:

{   "id":"1000000",   "name":"movies",   "children":[      {        "id":"1000001",        "name":"outdoor movies",        "children":[           {             "id":"1111",             "name":"outdoor skiing",             "parent_id":"1110",             "parents: [....these can stay here....]           }        ]      }   ] } 

can me out on how solve using recursion? thanks.

if you're okay using underscore, think you're looking for:

var flip = function(theobject, newobject, offset) {     offset ? offset++ : offset = 1;     var newobj = _.first(_.last(theobject.parents, offset));     newobject ? newobj.children = newobject : newobj.children = theobject;     if (offset < _.size(theobject.parents))     {         flip(theobject, newobj, offset);         return;     }     // @ point 'newobj' variable contains desired object }; 

here's fiddle

edit: due popular demand :) here's example without underscore.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -

jquery - Keeping Kendo Datepicker in min/max range -