Skip to content

Instantly share code, notes, and snippets.

@VillainsRule
Last active May 2, 2025 03:00
Show Gist options
  • Save VillainsRule/d603c30f76e3affbf2daa4c35599ab53 to your computer and use it in GitHub Desktop.
Save VillainsRule/d603c30f76e3affbf2daa4c35599ab53 to your computer and use it in GitHub Desktop.

tools for reverse engineering things that involve large trees that piss me off

find by key
function findByKey(object, key, seen = new Set(), path = '') {
    if (seen.has(object)) return undefined;
    seen.add(object);

    for (let k of Object.keys(object)) {
        let newPath = path ? `${path}.${k}` : k;

        if (k === key) {
            console.log(`found at: ${newPath}`);
            return object[k];
        }
        
        if (object[k] && typeof object[k] === 'object') {
            let result = findByKey(object[k], key, seen, newPath);
            if (result !== undefined) return result;
        }
    }
    
    return undefined;
}
find all by key
function findAllByKey(object, key, seen = new Set(), path = '') {
    try {
        if (seen.has(object)) return;
        seen.add(object);

        for (let k of Object.keys(object)) {
            let newPath = path ? `${path}.${k}` : k;

            if (k === key) {
                console.log(`found at: ${newPath}`);
                console.log(object[k]);
            }

            if (object[k] && typeof object[k] === 'object') {
                findAllByKey(object[k], key, seen, newPath);
            }
        }
    } catch (err) {
        console.warn(`Error traversing path "${path}":`, err);
    }
}
find by value
function findByValue(object, targetValue, seen = new Set(), path = '') {
    if (seen.has(object)) return undefined;
    seen.add(object);

    for (let [key, value] of Object.entries(object)) {
        let newPath = path ? `${path}.${key}` : key;

        if (value === targetValue) {
            console.log(`found at: ${newPath}`);
            return newPath;
        }

        if (value && typeof value === 'object') {
            let result = findByValue(value, targetValue, seen, newPath);
            if (result !== undefined) return result;
        }
    }

    return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment