Within the array provided below, there are parent items as well as children.
I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels.
For reference, you can view the fiddle here: 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)