javascript - Reorder a JS object in a child-parent structure -
i'm facing brain-breaker (at leats me) : json file 1 depth array of data objects this:
[ {"id":1, "name":"sport", "parent_id":0, "children":[]}, {"id":2, "name":"tennis", "parent_id":4, "children":[]}, {"id":3, "name":"climbing", "parent_id":5, "children":[]}, {"id":4, "name":"indoor", "parent_id":1, "children":[]}, {"id":5, "name":"outdoor", "parent_id":1, "children":[]}, {"id":6, "name":"bowling", "parent_id":4, "children":[]} ]
how can convert in tree-structure children put inside parent's children array? objects not in te right order, child can come before parent in array. (like id 2 , 3 in example)
this how need in end:
[ {"id":1, "name":"sport", "parent_id":0, "children": [ {"id":4, "name":"indoor", "parent_id":1, "children": [ {"id":2, "name":"tennis", "parent_id":4, "children":[]}, {"id":6, "name":"bowling", "parent_id":4, "children":[]}, ]}, {"id":5, "name":"outdoor", "parent_id":1, "children": [ {"id":3, "name":"climbing", "parent_id":5, "children":[]} ]}, ]} ]
any idea how achieve this?
i tried iterating on elements , pushing inside parents children array, when parent has been moved, next sibling can't find parent anymore...
i'm not sure why keen on writing inefficient o2 algorithms (nested for-loops), here 1 in o(n log n) time:
function treeify(nodes) { var indexed_nodes = {}, tree_roots = []; (var = 0; < nodes.length; += 1) { indexed_nodes[nodes[i].id] = nodes[i]; } (var = 0; < nodes.length; += 1) { var parent_id = nodes[i].parent_id; if (parent_id === 0) { tree_roots.push(nodes[i]); } else { indexed_nodes[parent_id].children.push(nodes[i]); } } return tree_roots; } var nodes = [ {"id":1, "name":"sport", "parent_id":0, "children":[]}, {"id":2, "name":"tennis", "parent_id":4, "children":[]}, {"id":3, "name":"climbing", "parent_id":5, "children":[]}, {"id":4, "name":"indoor", "parent_id":1, "children":[]}, {"id":5, "name":"outdoor", "parent_id":1, "children":[]}, {"id":6, "name":"bowling", "parent_id":4, "children":[]} ]; console.log(json.stringify(treeify(nodes), undefined, "\t"));
Comments
Post a Comment