DEV Community

Suvadeep Majumdar
Suvadeep Majumdar

Posted on

2 1

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay