Search key in nested complex JSON
<p>I have to search for a key in nested JSON by JavaScript or by jQuery. In my JSON object all the keys are unique. I tried some solutions myself but they did not work.
Here is my code:</p>

<pre><code>json = {
    "app": [{
        "Garden": {
            "Flowers": {
                "Red flower": "Rose",
                "White Flower": "Jasmine",
                "Yellow Flower": "Marigold"
            }
        },
        "Fruits": {
            "Yellow fruit 1": "Mango",
            "Green fruit 2": "Guava",
            "White Flower 3": "groovy"
        },
        "Trees": {
            "label": {
                "Yellow fruit 2": [{"type a":"Pumpkin", "type b": "Banana",..}],
                "White Flower 2": ["Bogan 1", "Bogan 2", ...] 
            }
        }],...
    }
</code></pre>

<p>How can I search for a specific key in given object?</p>

<p>If I pass <code>lookup(json, "type a")</code> it should return <code>"Pumpkin"</code>, OR If I search  for <code>"White Flower 2"</code> it should return  <code>["Bogan 1", "Bogan 2", ...]</code> </p>

<p>Here is my try, which is not working:</p>

<pre><code>function lookup(obj, k){
    for (key in obj){
        value = obj[key];
        if (k == key) return [k, value];
        if (type(value) == "Object"){
            var y = lookup(value, k);
            if (y &amp;&amp; y[0]== k)return y;
        }
        if(type(value) == "Array"){
            for (i in value)
            {
                var x = lookup(value[i], k);
                if (x &amp;&amp; x[0]== k)return x; 
            }
        }
        console.log(key, value);
        return null;
    } 
}
</code></pre>

<p>To find the type of the object, I'm using this code:</p>

<pre><code>function type(object){
    var stringConstructor = "test".constructor;
    var arrayConstructor = [].constructor;
    var objectConstructor = {}.constructor;

    if (object === null) {
        return "null";
    }
    else if (object === undefined) {
        return "undefined";
    }
    else if (object.constructor === stringConstructor) {
        return "String";
    }
    else if (object.constructor === arrayConstructor) {
        return "Array";
    }
    else if (object.constructor === objectConstructor) {
        return "Object";
    }
    else {
        return "null";
    }
}
</code></pre>