我从API调用中收到一个对象。我要检查:
假设我期待以下对象:
success.response.data.users.items.list
现在我想知道此list
对象是否存在。
我尝试过:
typeof success.response.data.users.items.list !== "undefined"
我得到的错误:TypeError: Cannot read property 'data' of undefined
success.hasOwnProperty("response.data.users.items.list")
由于hasOwnProperty
显然不能检查多级对象,所以它总是计算为false。
success.response.data.users.items.hasOwnProperty("list")
我得到的错误:TypeError: Cannot read property 'data' of undefined
是否有任何现代且快速的方法来检查这一点?
如果您愿意,可以选择optional chaining:
success?.response?.data?.users?.items?.list || []