Skip to content

Instantly share code, notes, and snippets.

@darsain
Last active November 28, 2016 12:24
Show Gist options
  • Save darsain/dcf6ef9b0e8b7048493a33ae2dc183f4 to your computer and use it in GitHub Desktop.
Save darsain/dcf6ef9b0e8b7048493a33ae2dc183f4 to your computer and use it in GitHub Desktop.
Log key and value of a property containing a string in an object searched recursively while ignoring circular references.
function search(needle, obj, ignore = null) {
needle = needle.toLowerCase();
const objs = new Set();
_search(obj);
function _search(obj, root = '') {
if (!obj || typeof obj !== 'object' || objs.has(obj)) {
return;
}
objs.add(obj);
for (let [key, value] of Object.entries(obj)) {
let path = `${root}/${key}`;
if (ignore && path.indexOf(ignore) !== -1) {
continue;
}
const isString = typeof value === 'string';
const keyMatches = key.toLowerCase().indexOf(needle) !== -1;
const valueMatches = isString && value.toLowerCase().indexOf(needle) !== -1;
if (keyMatches || valueMatches) {
console.log(`${path}:`, value);
}
if (value && typeof value === 'object') {
_search(value, path);
}
}
}
}
const obj = {
a: 1,
b: {
c: {
d: 'hello world'
}
},
e: 2,
f: {
hello: 'world'
arr: ['hello', 'world']
},
g: {
h: {
i: 'ignored hello'
}
}
};
// log all `hello` occurences in `obj`, ignoring `/g/h` path
search('hello', obj, '/g/h');
// logs:
// > /b/c/d: hello world
// > /f/hello: world
// > /f/arr/0: hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment