Last active
November 28, 2016 12:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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