Created
March 23, 2021 19:42
-
-
Save karlvr/1cb1eaab62a06137c1dd558c65840fe6 to your computer and use it in GitHub Desktop.
Search a JavaScript object for a string
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(ob, needle, path = [], seen = new Map()) { | |
if (seen.has(ob)) { | |
return | |
} | |
seen.set(ob, true) | |
for (const key of Object.keys(ob)) { | |
if (typeof ob[key] === 'string') { | |
if (ob[key].indexOf(needle) !== -1) { | |
const pathDesc = [...path, key].map(pathKey => Number(pathKey) == pathKey ? `[${pathKey}]` : `.${pathKey}`).join('').substring(1) | |
console.log(`Found needle ${pathDesc} = ${ob[key]}`) | |
} | |
} else if (typeof ob[key] === 'object' && ob[key]) { | |
search(ob[key], needle, [...path, key], seen) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment