I am trying to create a function that can iterate through an object and match nodes names against a certain serach string, then if a match is found it should retrun the relevant path of the matching child node like "root/child/child/match"
This is what i've got so far:
function findNode (obj, str)
{
var root = "root/", regx = new RegExp(str, "gi");
function test(node) {return regx.test(node)};
function isObject(obj) {return typeof(obj) == "object"}
function hasSOs(obj) //check for existance of sub objects
{
if (isObject(obj)) for (var i in obj) if (isObject(obj[i])) return true;
return false;
}
function searchDCs(obj) //search direct objects
{
for (var i in obj) if (test(i)) return i;
return false;
}
function iterate(node)
{
if (searchDCs(node)) return root + searchDCs;
else if (hasSOs(node))
{
for (var i in node)
{
if (isObject(node[i]))
{
if (searchDCs(node[i])) return root + i + "/" + searchDCs(node[i]);
else
{
if (iterate(node[i])) return root + i + "/" + iterate(node[i]);
else return false;
}
}
}
}
else return false;
}
console.log(iterate(obj));
}
It doesn't seems to be working properly, any help would be appreciated.
Edit:
- I need it to return all search results not just the first match.
- I
need it to iterate through sub arrays and return result like
root/child/child[3]/match
where [3] is the 3d child in the root.child.child <- array(0, 1, 2, {object}).