DEV Community

Suvadeep Majumdar
Suvadeep Majumdar

Posted on

Find path to a particular value in an Object

This is my first post, so I would expect you to consider naivety in my language.

My Approach
We need to think recursively to reach to the point in the object where the value exists.
For each key we encounter, there are two condition,

  1. Either its value is equal to out value
  2. It's an object, and we need to dive into it. You guys thinking, what if its value is not an object and not equal to our value, you can ignore that, at least that's what I did. For each recursive call, pass the current object and the value as parameter. Alongside also pass the array containing current path, since we are interested in printing path.

That's it!

My Code

var obj = {
    a: {
        b:1,
        c: {
            d: 10
        }
    }, e: {
        f: 5,
        g: {
            h: "hii"
        }, 
        i: {
            j: {
                k:3,
                l: {
                    m: 20,
                },
                n: {
                    o:10
                },
                p: "hello"
            }
        }
    }
}
var arr = []
function findPath (obj, val) {
    arr = [];
    for(let x in obj) {
        if(obj[x] === val) {
            arr.push(x);
        } else if(typeof obj[x] === 'object') {
            findUtil(obj[x], val, x)
        }
    }
    return arr;
}
function findUtil(obj1, val, ...y) {
    for(let x in obj1) {
        if(obj1[x] === val) {
            arr = [...y, x]
        } else if(typeof obj1[x] === 'object') {
            findUtil(obj1[x], val, ...[...y, x])
        }
    }
}
console.log(findPath(obj, "hello").length ? findPath(obj, "hello").join("") : "Not Present")
console.log(findPath(obj, "hii").length ? findPath(obj, "hii").join("") : "Not Present")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)