次のようなことができます。
response && response.foo && response.foo.bar && response.foo.bar.baz
ネストされたプロパティのいずれかが存在しない場合は、undefined
それ以外の場合は の内容が返されますresponse.foo.bar.baz
。
この関数を使用できる代替手段:
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;
}
}
使用法:
getNestedProperty(response, ['foo', 'bar', 'baz']);