Skip to content

Instantly share code, notes, and snippets.

@iskolbin
Last active September 28, 2021 16:48
Show Gist options
  • Save iskolbin/688b32047dbad7c2f7ae95fcd255fdae to your computer and use it in GitHub Desktop.
Save iskolbin/688b32047dbad7c2f7ae95fcd255fdae to your computer and use it in GitHub Desktop.
find key or value in object
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