简体   繁体   中英

Accessing Nested Objects in JSON Feed and Handling Undefined

My problem is this:

I have an end point that will return JSON containing a structure named: the_data_i_want

If the server detects there is a value for the_data_i_want then it returns something like this:

{
    "sample": {
        "title": "The Title",
        "foo": {
            "Bar": {
                "Baz": {
                    "Qux": {
                        "the_data_i_want": "DATA PARTY!!!!"
                    }
                }
            }
        }
    }
}

If the server detects that the_data_i_want is empty, the JSON it returns looks something like this:

{
    "sample": {
        "title": "The Title"
    }
}

My problem is that because any segment of the chain sample.foo.Bar.Baz.Qux.the_data_i_want my be undefined i end up doing these Crazy chains of checks on each step through the json structure where i look and first see if it's undefined, then if it isn't, i try the next one and next one until i get to the_data_i_want and it seems wrong.

The question:

Is there a "correct" way to handle this? What would i do in the even the nesting is arbitrarily deep? I'm open to using jQuery.

thank you!

May be this might work.. But there may be better methods out there..

In this approach I have all the keys in an array and check them in a loop..

var obj = {
    "sample": {
        "title": "The Title",
        "foo": {
            "Bar": {
                "Baz": {
                    "Qux": {
                        "the_data_i_want": "DATA PARTY!!!!"
                    }
                }
            }
        }
    }
};

var arr = ["foo", "Bar", "Baz", "Qux", "the_data_i_want"];
var arr1 = ["foo", "Bar", "Baz", "Qux", "the_data_i_want", "ding"];

checkKey('Object 1' , arr);
checkKey('Object 2 ' ,arr1);

function checkKey(str ,arr) {
    if (obj && obj.sample) {
        var k = obj.sample;
        var i = 0;
        for (var i = 0; i < arr.length; i++) {
            if (k[arr[i]]) {
                k = k[arr[i]];
                if (i === arr.length - 1) {
                    alert('Data Found :: ' + k);
                }
            }
            else {
                alert('No such Key in :: ' + str );
                break;
            }
        }
    }
    else {
         alert('No such Key in :: ' + str );
    }
}​

Check Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM