Skip to content

Instantly share code, notes, and snippets.

@clupasq
Created October 12, 2017 14:21
Show Gist options
  • Save clupasq/acbdf89a619fe527eeebd0ffd7f7170c to your computer and use it in GitHub Desktop.
Save clupasq/acbdf89a619fe527eeebd0ffd7f7170c to your computer and use it in GitHub Desktop.
Search using a regex inside a deeply nested JS Object
var searchObject = function(o, expr, callback, path, visited) {
try{
visited = visited || new Set();
path = path || '';
if (visited.has(o)) { return; }
if (!o) { return; }
visited.add(o);
if (typeof o === 'string') {
if (o.match(expr)) {
callback(path);
}
} else if (typeof o === 'object') {
Object.keys(o).forEach(function(k){
if (o.hasOwnProperty(k)){
searchObject(o[k], expr, callback, path + '/' + k, visited);
}
});
}
} catch (e) {
console.error(['Could not access ' + path, e]);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment