简体   繁体   中英

Looking up nested properties in AJAX response, a case for try/catch?

So I'm writing a browser application that fetches data from many different public APIs (via JSONP) and uses that data to decorate my local records.

Yeah, this could be done server-side beforehand but I'm not there yet.

I've never used try/catch in JavaScript before. In trying to lookup response.foo.bar.baz in a response that's liable to change, would this be a good time to use it?

Alternatively, is there a more elegant way to lookup deeply nested properties and not throw an error if it can't be found?

You could do something like this:

response && response.foo && response.foo.bar && response.foo.bar.baz

If one of the nested properties doesn't exist it will return undefined else it will return the contents of response.foo.bar.baz .

Alternative you could use this function:

function getNestedProperty(firstObject, propertiesArray)
{
    if(firstObject instanceof Object)
    {
        var currentObject = firstObject;
        for(var i = 0; i < propertiesArray.length; i++)
        {
            if(currentObject.hasOwnProperty(propertiesArray[i]))
            {
                currentObject = currentObject[propertiesArray[i]];
            }
            else
            {
                return false;
            }
        }
        return currentObject;
    }
    else
    {
        return false;
    }
}

Usage:

getNestedProperty(response, ['foo', 'bar', 'baz']);

It's probably easier to write:

try {
    response.foo.bar.baz;
}
catch (e) {
    //oops
}

Than:

if( response && response.foo && response.foo.bar && "baz" in response.foo.bar ) {

}
else {
    //oops
}

Given that the alternative is something like:

if ('foo' in response &&
    'bar' in response.foo &&
    'baz' in response.foo.baz)
{
    ...
}

it sounds like a try / catch block might be a good option in this case!

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