How to get the path from javascript object from key and value

I have a javascript object width depth.

I need to know the exact path from this key within the object ex: “obj1.obj2.data1”

I already know the key is data1, the value is 123.

My javascript object look like this

{
    obj1: {
        obj2: {
            data1: 213,
            data2: "1231",
            obj3: {
                data: "milf"
            }
        }
    },
    obj4: {
        description: "toto"
    }
}

How could I achieve that ?

here is a jsfiddle : http://jsfiddle.net/3hvav8xf/8/ I am trying to implement getPath.

Answer

I think recursive function can help to you (Updated version, to check value)

function path(c, name, v, currentPath, t){
    var currentPath = currentPath || "root";

    for(var i in c){
      if(i == name && c[i] == v){
        t = currentPath;
      }
      else if(typeof c[i] == "object"){
        return path(c[i], name, v, currentPath + "." + i);
      }
    }

    return t + "." + name;
};

console.log(path({1: 2, s: 5, 2: {3: {2: {s: 1, p: 2}}}}, "s", 1));

Leave a Reply

Your email address will not be published. Required fields are marked *