Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  83] [ 7]  / answers: 1 / hits: 137270  / 13 Years ago, fri, february 3, 2012, 12:00:00

I have and object literal that is essentially a tree that does not have a fixed number of levels. How can I go about searching the tree for a particualy node and then return that node when found in an effcient manner in javascript?



Essentially I have a tree like this and would like to find the node with the title 'randomNode_1'



var data = [
{
title: 'topNode',
children: [
{
title: 'node1',
children: [
{
title: 'randomNode_1'
},
{
title: 'node2',
children: [
{
title: 'randomNode_2',
children:[
{
title: 'node2',
children: [
{
title: 'randomNode_3',
}]
}
]
}]
}]
}
]
}];

More From » javascript

 Answers
7

Basing this answer off of @Ravindra's answer, but with true recursion.



function searchTree(element, matchingTitle){
if(element.title == matchingTitle){
return element;
}else if (element.children != null){
var i;
var result = null;
for(i=0; result == null && i < element.children.length; i++){
result = searchTree(element.children[i], matchingTitle);
}
return result;
}
return null;
}


Then you could call it:



var element = data[0];
var result = searchTree(element, 'randomNode_1');

[#87654] Thursday, February 2, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;