Skip to content

Instantly share code, notes, and snippets.

@karlvr
Created March 23, 2021 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlvr/1cb1eaab62a06137c1dd558c65840fe6 to your computer and use it in GitHub Desktop.
Save karlvr/1cb1eaab62a06137c1dd558c65840fe6 to your computer and use it in GitHub Desktop.
Search a JavaScript object for a string
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