Find the bellow parent child tree object I have created. I need to find the root parent of a given child id. For example child id - 242 root parent id is 238. There are similar questions have been asked and this is the one I found very similar to my question.
Convert parent-child array to tree
I have change the original code a bit But not working for child element. The issue is here. when it comes the recursive function with rootNode.children
for loop will not execute since it does not loop through children. But if I change the for loop for (var i = 0; i < rootNode.length; i++)
to for (var i = 0; i < rootNode.children.length; i++)
then it break on first loop since does not have children. I'm sure with small code change this can make work.
var getParent = function (rootNode, rootId) {
if (rootNode.id === rootId)
return rootNode;
//for (var i = 0; i < rootNode.children.length; i++) -- original code line not working first time
for (var i = 0; i < rootNode.length; i++) {
var child = rootNode[i];
if (child.id === rootId)
return child;
if (typeof child.children !== 'undefined')
var childResult = getParent(child, rootId);
if (childResult != null) return childResult;
}
return null;
};
var mytree = [
{
"id": 245,
"parent": "0",
"title": "project1",
"children": [
{
"id": 246,
"parent": "245",
"title": "sub task 1"
}
]
},
{
"id": 238,
"parent": "0",
"title": "project2",
"children": [
{
"id": 240,
"parent": "238",
"title": "sub task 2"
},
{
"id": 242,
"parent": "238",
"title": "sub task 3",
"children" : [
{
"id": 241,
"parent": "242",
"title": "sub task 3.1"
}
]
}
]
},
{
"id": 173,
"parent": "0",
"title": "project3"
}
];
console.log(JSON.stringify(getParent(mytree, 238)['title']));
console.log(JSON.stringify(getParent(mytree, 241)));