Javascript/JSON get path to given subnode?

So you have a variable with the value “key3”, and you want to know how to access this property dynamically, based on the value of this string?

var str = "key3";
data["key1"]["children"][str];

EDIT

Wow, I can’t believe I got this on the first try. There might be some bugs in it, but it works for your test case

LIVE DEMO

var x = data.key1.children.key4;

var path = "data";
function search(path, obj, target) {
    for (var k in obj) {
        if (obj.hasOwnProperty(k))
            if (obj[k] === target)
                return path + "['" + k + "']"
            else if (typeof obj[k] === "object") {
                var result = search(path + "['" + k + "']", obj[k], target);
                if (result)
                    return result;
            }
    }
    return false;
}

var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']

Leave a Comment