I am trying to Search in a tree, but my results are not as expected. Can any body please help?
function treeSearch(searchedValue,ExceptionTree:){
let result = {};
var childrenKeys = Object.keys(ExceptionTree);
for(let i = 0; i< childrenKeys.length;i++){
if(childrenKeys[i].toLowerCase().indexOf(searchedValue) >=0 || Object.keys( treeSearch( ExceptionTree[childrenKeys[i]] , searchedValue ) ).length >=0 )
result[childrenKeys[i]] = ExceptionTree[childrenKeys[i]];
}
return result;
}
Below is the sample Input:
var myTree= {
"North America": {
"Canada": {
"VanCouver": 1,
"Ottawa": 2
},
"US": {
"Florida": 3,
"Texas": 4
}
},
"Asia": {
"India": {
"Mumbai": 5,
"Delhi": 6
},
"China": {
"Shanghai": 9,
"Beijing": 10
}
}
}
If I call
treeSearch("Texas",myTree)
the result should be
{
"North America": {
"USA": {
"Texas":4
}
}
}
I am either getting the entire tree returned or an empty tree. Any suggestions?