简体   繁体   English

在AJAX响应中查找嵌套属性(尝试/捕获的情况)?

[英]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. 因此,我正在编写一个浏览器应用程序,该应用程序从许多不同的公共API(通过JSONP)中获取数据,并使用该数据来修饰我的本地记录。

Yeah, this could be done server-side beforehand but I'm not there yet. 是的,这可以事先在服务器端完成,但我还没有。

I've never used try/catch in JavaScript before. 我以前从未在JavaScript中使用过try / catch。 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? 尝试在易于更改的response.foo.bar.baz中查找response.foo.bar.baz时,是使用它的好时机吗?

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 . 如果其中一个嵌套属性不存在,它将返回undefined否则它将返回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! 听起来在这种情况下, try / catch块可能是一个不错的选择!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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