Created
July 7, 2025 20:34
-
-
Save FlyInk13/ac8796043aa3823cbdb070b4cbd82016 to your computer and use it in GitHub Desktop.
Код который ищет путь от window до объекта по наличию ключа в нем
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
const findKeyPath = (obj, qKey, depthLimit = 30) => { | |
const seen = new Set(); | |
const queue = [ [ obj, [], depthLimit ] ] | |
while (queue.length) { | |
const [node, path, depthLimit] = queue.shift(); | |
if (depthLimit < 0) continue; | |
if (seen.has(node)) continue; | |
if (typeof node !== 'object') continue; | |
if (!node) continue; | |
const keys = Object.keys(node); | |
if (keys.includes(qKey)) { | |
return [...path, qKey]; | |
} | |
seen.add(node); | |
keys.forEach((key) => { | |
queue.push([ | |
node[key], | |
[...path, key], | |
depthLimit - 1, | |
]); | |
}); | |
} | |
return null; | |
} | |
findKeyPath(window, 'docs-bold', 3) // Выдаст: ['$Qb', 'D', 'docs-bold'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment