Created
May 18, 2023 09:47
-
-
Save whchi/059b9dba8a761e381c082ce9351400a3 to your computer and use it in GitHub Desktop.
find object members contain specific string with depth
This file contains hidden or 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 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