简体   繁体   中英

Find parent and child from array

In the array below, some of the items are parent and some of them are its children.

I want to find parents(with depth 0) and their childrens(nested with depth 1 -- depth2 --- depth 3) and then push to another array.

So far what I did only works for depth 0 and depth 1, don't know what to do with more depths.

Here's the fiddle : http://jsfiddle.net/s3x5f4ap/2/

 const comments = [ { "depth": 0,"id": "f35vz2f"}, { "depth": 0,"id": "f359354"}, { "depth": 1,"id": "f35e0b0", "parent_id": "f359354" }, { "depth": 2, "id": "f35ji24", "parent_id": "f35e0b0"}, { "depth": 2, "id": "f35rnwb", "parent_id": ""}, { "depth": 2, "id": "f35ojh4", "parent_id": "f35e0b0" }, { "depth": 3, "id": "f35lmch", "parent_id": "f35ji24"}, { "depth": 3, "id": "f35kl96", "parent_id": "f35ji24"}] const parent = comments.filter(cm => cm.depth == 0); final = []; final = parent; comments.forEach(a => { final.forEach(c => { if (c.id == a.parent_id) { c.child = [] c.child.push(a); } }) }) console.log(final)

You could collect all relations of the nodes and build a tree.

 var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }], tree = function (data, root) { var t = {}; data.forEach(o => { Object.assign(t[o.id] = t[o.id] || {}, o); t[o.parent_id] = t[o.parent_id] || {}; t[o.parent_id].children = t[o.parent_id].children || []; t[o.parent_id].children.push(t[o.id]); }); return t[root].children; }(data, undefined); console.log(tree);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

If you want to end up with a tree-like structure, I would do something like:

 var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }]; var attach_children_to_item = function (item, data) { item.children = data.filter(x => x.parent_id == item.id) .map(x => attach_children_to_item(x, data)); return item; }; var tree = data.filter(x => x.depth == 0) .map(x => attach_children_to_item(x, data)); console.log(tree);

Note that you will have missing items if the depth > 0 and the parent_id does not correspond to another item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM