I’m writing a code where I’ve got a nested family tree and I want to create a JSON array with the same. Currently, I can get a parent value in the newly created JSON, but I’m looking for a way to get the ancestor Id.
Here is my code.enter code here
const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3,
},
],
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
},
],
},
],
},
],
},
],
};
idArray = [];
function func(obj, parent) {
idArray.push({
id: obj.id,
name: `${obj.id} ${parent ? `child of ${parent}` : ""}`,
parentId: parent
});
if (!obj.children) {
return;
}
obj.children.forEach((child) => func(child, obj.id));
}
func(myObj);
console.log(idArray);
Here under the parent
I want a new key grandparent
that shows the grandparent id. please lemme know how I can get this. And, also Is there a way that I can get the result without using a global variable and by just looping over data and returning the final array? like console.log(JSON.stringify(func(myObj)))
.
Thanks
2
Answers
Generally, if you want to keep track of more than 1 ancestor, a B-Tree is an ideal way of managing that. It is much easier to find the parent of any node on any level.
Here is a resource where you can learn more about B-Trees. Building a B-Tree in JavaScript
You should check and operate every children on child.
If a child have children then you must recall same function.
See ‘finder’ function below.
output