I am currently working on constructing a family tree that can have an infinite number of levels for parents and children. I am also interested in finding relationships like brothers, sisters, cousins, and so on. However, I'm facing some confusion when it comes to creating an array in JavaScript based on data that only provides the parents of each person.
Within a MongoDB Collection named "Users," here are some of the entries:
{ id: 1, name: "Target", parents: [3,4] }
{ id: 2, name: "Wife" }
{ id: 3, name: "Dad", parents: [5,6] }
{ id: 4, name: "Mom" }
{ id: 5, name: "Dads Dad", parents: [7,8] }
{ id: 6, name: "Dads Mom" }
{ id: 7, name: "Dads Dads Dad", parents: 9 }
{ id: 8, name: "Dads Dads Mom" }
{ id: 9, name: "Dads Dads Dads Dad" }
{ id: 10, name: "Son", parents: [1, 2] }
{ id: 11, name: "Sons Son", parents: [10] }
{ id: 12, name: "Sons Sons Son", parents: [11] }
{ id: 13, name: "Brother", parents: [3,4] }
{ id: 14, name: "Brothers Son", parents: [13] }
{ id: 15, name: "Uncle", parents: [5,6] }
{ id: 16, name: "Aunt", parents: [5,6] }
{ id: 17, name: "Daughter", parents: [5,6] }
While I can easily loop through each child using their IDs and output them, it doesn't provide a structured view of children's children; instead, it just loops and outputs.
getChildren = function(id) {
var children = Users.find({parents: id});
children.forEach(function(child) {
console.log(child);
getChildren(child.id);
});
};
I've been attempting to create two global variables called ascendants
and descendants
to organize parents, grandparents, etc., along with nesting their respective children inside (for siblings and nephews) and similarly for descendants. However, this has become complex due to multiple nests and the need to add entries within others.
If someone could assist me in structuring this information, I believe I could use it to create an HTML/CSS family tree. To handle non-parent/child relations, I may have to conditionally loop again?
descendents = {
10: { // son
11: { // grandson
12: {} // great grandson
}
},
17: { // daughter
}
}