showing results for - "find parent and child from array javascript"
Maina
16 Oct 2020
1var 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" }],
2    tree = function (data, root) {
3        var t = {};
4        data.forEach(o => {
5            Object.assign(t[o.id] = t[o.id] || {}, o);
6            t[o.parent_id] = t[o.parent_id] || {};
7            t[o.parent_id].children = t[o.parent_id].children || [];
8            t[o.parent_id].children.push(t[o.id]);
9        });
10        return t[root].children;
11    }(data, undefined);
12
13console.log(tree);
14