i have object structured this:
[ { "id": 34, "parent": 0, "title": "level 1 a", "children": [] }, { "id": 35, "parent": 0, "title": "level 1 b", "children": [ { "id": 36, "parent": 35, "title": "level 2 a", "children": [ { "id": 37, "parent": 36, "title": "level 3 a", "children": [] }, { "id": 38, "parent": 36, "title": "level 3 b", "children": [] } ] } ] } ] and i'm trying loop through , make "title" key end this:
[ { "level 1 a": { "id": 34, "parent": 0, "title": "level 1 a", "children": [] } }, { "level 1 b": { "id": 35, "parent": 0, "title": "level 1 b", "children": [ { "level 2 a": { "id": 36, "parent": 35, "title": "level 2 a", "children": [ { "level 3 a": { "id": 37, "parent": 36, "title": "level 3 a", "children": [] } }, { "level 3 b": { "id": 38, "parent": 36, "title": "level 3 b", "children": [] } } ] } } ] } } ] i tried this, doesn't go through children arrays level 1 elements updated:
(var = 0, l = response.length; < l; i++) { map[response[i].title] = response[i]; } i believe need use recursion, i'm having trouble figuring out how done javascript. in advance suggestions.
you need update code following
function updatearray(arr) { var updatedresponse = []; (var = 0, l = arr.length; < l; i++) { var obj = {}; if(arr[i].children !== undefined) { arr[i].children = updatearray(arr[i].children); } obj[arr[i].title] = arr[i]; updatedresponse.push(obj); } return updatedresponse; } var updatedarray = updatearray(response); for reference - http://plnkr.co/edit/bxlol9vhxuxzolzkhbte?p=preview
Comments
Post a Comment