How can I utilize my getChildren() function to create a larger function that takes my two main arrays objs
and objRefs
, and generates a single array of objs showcasing their parent/child relationship?
Below are the two primary data arrays:
const objs = [
{ name: "Kevin", age: 5, id: 1 },
{ name: "Matt", age: 53, id: 5 },
{ name: "Marry", age: 30, id: 2 },
{ name: "Leslie", age: 21, id: 3 },
{ name: "Sarah", age: 46, id: 4 },
{ name: "Heather", age: 37, id: 6 },
{ name: "Cory", age: 19, id: 7 },
]
const objRefs = [
{ parent_id: 5, obj_id: 7 }, // cory child of matt
{ parent_id: null, obj_id: 6 }, // matt root
{ parent_id: null, obj_id: 4 }, // sarah root
{ parent_id: null, obj_id: 5 }, // heather root
{ parent_id: 5, obj_id: 3 }, // leslie child of matt
{ parent_id: 4, obj_id: 2 }, // mary child of sarah
{ parent_id: 3, obj_id: 1 }, // kevin child of leslie
]
The objective is to execute a function called getFamilyTree()
which should give me the following output...
const tree = [
{
id: 5,
name: "Matt",
age: 53,
children:[
{
id: 3,
name: "Leslie",
age: 21,
children:[
{
id: 1,
name: "Kevin",
age: 5,
children:[ ]
}
]
},
{
id: 7,
name: "Cory",
age: 19,
children:[ ]
}
]
},
{
id: 6,
name: "Heather",
age: 37,
children:[ ]
},
{
id: 4,
name: "Sarah",
age: 46,
children:[
{
id: 2,
name: "Marry",
age: 30,
children:[ ]
}
]
}
]
I have a function that returns all children for a given parent node id, but I'm uncertain how to structure a function that will return the entire tree as shown in my example.
function getChildren(parent_id) {
let children = []
for (var i = 0; i < objRefs.length; i++) {
const ref = objRefs[i]
if (ref.parent_id === parent_id) {
const obj = objs.find(obj => {
return obj.id === ref.obj_id
})
children.push(obj)
}
}
return children
}
function getFamilyTree() {
let result = []
... // build recursive family tree
return result
}