Skip to content

Instantly share code, notes, and snippets.

@whchi
Created May 18, 2023 09:47
Show Gist options
  • Select an option

  • Save whchi/059b9dba8a761e381c082ce9351400a3 to your computer and use it in GitHub Desktop.

Select an option

Save whchi/059b9dba8a761e381c082ce9351400a3 to your computer and use it in GitHub Desktop.
find object members contain specific string with depth
function searchObject(object, searchTerm, maxDepth, currentPath = [], currentDepth = 0) {
if (currentDepth > maxDepth) {
return;
}
for (let key in object) {
try {
if (key.toLowerCase().includes(searchTerm.toLowerCase())) {
console.log(`Path: ${currentPath.join('.')}.${key}`);
}
if (typeof object[key] === 'object' && object[key] !== null) {
searchObject(object[key], searchTerm, maxDepth, currentPath.concat([key]), currentDepth + 1);
}
} catch (error) {
// Catch any errors, such as security access errors, here.
}
}
}
searchObject(window, 'shop', 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment