get a path of deeply nested object by key

Viewed 145

I have a deeply nested object

const myObject = {
    a: {
        b: {
            c: [
                {
                    t: {finallyHere: 'no!'}
                },
                {
                    d: {finallyHere: 'yes!'}
                },
            ]
        }
    }
}

my output object would look like, output = [a, b, c, 1, d] the function I will pass is getPath(myObject, 'd')

function I am trying so far,

function getPath(obj, key) {
    paths = []

    function getPaths(obj, path) {
        if (obj instanceof Object && !(obj instanceof Array)) {
            for (var k in obj){
                paths.push(path + "." + k)
                getPaths(obj[k], path + "." + k)
            }
        }
    }

    getPaths(obj, "")
    return paths.map(function(p) {
        return p.slice(p.lastIndexOf(".") + 1) == key ? p.slice(1) : ''
    }).sort(function(a, b) {return b.split(".").length - a.split(".").length;})[0];
}

for which I am getting undefined, please help with the output

1 Answers

You could take an iterative and recursive approach and check if the value is an object and if the key exists.

If not iterate the keys and return if the nested call of the function returns a truthy value and return immediately.

const
    getPath = (o, target) => {
        if (!o || typeof o !== 'object') return;
        if (target in o) return [target];
        for (const k in o) {
            const temp = getPath(o[k], target);
            if (temp) return [k, ...temp];
        }
    };
    object = { a: { b: { c: [{ t: { finallyHere: 'no!' } }, { d: { finallyHere: 'yes!' } } ] } } };
    
console.log(getPath(object, 'd'));

Related