algorithm - Javascript Recursion Tree Building -
i having issue building tree flat array. building category -> subcategory tree in parent has subcategories array.
here flat array like:
[ { "id": 1 }, { "id": 5, }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 1 }, { "id": 42, "parent_id": 5 }, { "id": 67, "parent_id": 5 } ]
and need result look:
[ { "id":1, "subcategories":[ { "id":2, "parent_id":1 }, { "id":3, "parent_id":1 } ] }, { "id":5, "subcategories":[ { "id":42, "parent_id":5 }, { "id":67, "parent_id":5 } ] } ]
i have tried recursively recursively searching children , attaching array , continuing until hit bottom of barrel getting cyclic structure. appears parent_id in traverse id of parent... ideas:
tree(passinginflatobjecthere); function toplevel (data) { let blob = []; data.foreach((each) => { if (!each.parent_id) { blob.push(each); } }); return blob; } function tree (data) { let blob = toplevel(data).map(function (each) { each.subcategories = traverse(data, each.id); return each; }); return blob; } function traverse (data, parent_id) { let blob = []; if (!parent_id) { return blob; } data.foreach((each) => { if (each.id === parent_id) { each.subcategories = traverse(data, each.id); blob.push(each); } }); return blob; }
i don’t want fix problem take full advantage of es6
first of toplevel
function can rewritten this:
function toplevel(data) { return data.filter(node => !node.parent_id); }
neat isn’t it? recommend changing tree
consistency that’s of course stylistic.
function tree(data) { return toplevel(data).map(each => { each.subcategories = traverse(data, each.id); return each; }); }
no logic issues far. traverse
, however, contains one, when check each.id === parent_id
. this, functions searches node id parent_id
. mistake. wanted each.parent_id === parent_id
.
your issue solved now. stop reading if bother you. take advantage of filter
here , remove superfluous exit , rewrite function to:
function traverse(data, parentid) { const children = data.filter(each => each.parent_id === parentid); children.foreach(child => { child.subcategories = traverse(data, child.id); }); return children; }
Comments
Post a Comment