Last active
September 28, 2021 16:48
-
-
Save iskolbin/688b32047dbad7c2f7ae95fcd255fdae to your computer and use it in GitHub Desktop.
find key or value in object
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 findKey(obj, key, callback = path => {console.warn(JSON.stringify(path));}, eq = (a,b) => a===b, path = [], visited = new Set()) { | |
if (!obj || visited.has(obj) || typeof obj !== "object") return; | |
visited.add(obj); | |
for (const k in obj) { | |
path.push(k); | |
try { | |
if (eq(k, key)) callback(path.slice()); | |
findKey(obj[k], key, callback, eq, path, visited); | |
} catch (e) { | |
} | |
path.pop(); | |
} | |
} | |
function findValue(obj, value, callback = path => {console.warn(JSON.stringify(path));}, eq = (a,b) => a===b, path = [], visited = new Set()) { | |
if (!obj || visited.has(obj) || typeof obj !== "object") return; | |
visited.add(obj); | |
for (const k in obj) { | |
path.push(k); | |
try { | |
if (eq(obj[k], value)) callback(path.slice()); | |
findValue(obj[k], value, callback, eq, path, visited) | |
} catch (e) { | |
} | |
path.pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment