What i'm trying to achieve is to create a function that would help me to quickly check the existance of a given property within a deeply nested javascript object, api or library and return the results as relevant paths such as: root/child/child/match
.
Here's what i've got so far:
function findNode(obj, str) {
var results = [], regx = new RegExp(str, "gi");
function innerFind(obj, str, currentPath) {
var i, propName, prop, result;
if (toString.call(obj) === "[object Array]") {
for (i = 0; i < obj.length; i++) {
if (typeof obj[i] === "object") {
innerFind(obj[i], str, currentPath + "[" + i + "]/");
}
}
} else {
for (propName in obj) {
if (regx.test(propName)) {
results.push(currentPath + propName + "/");
}
prop = obj[propName];
if (typeof prop === "object") {
innerFind(prop, str, currentPath + propName + "/");
}
}
}
}
if (typeof obj === "object") {
innerFind(obj, str, "root/");
}
return results;
}
It works perfectly on small to medium sized objects, however it fails on larger objects with the error: RangeError: Maximum call stack size exceeded
. I understand that the error was thrown because the function innerFind
was called numerous times from within itself.
So my question is, how to make the above function work without getting the RangeError
error? and is there a better more efficient way of doing this?