Reputation: 2738
I receive an object from an API call. I want to check:
Let's say that I'm expecting the following object of objects:
success.response.data.users.items.list
Now I want to know if this list
object exists or not.
I have tried:
typeof success.response.data.users.items.list !== "undefined"
Error I got: TypeError: Cannot read property 'data' of undefined
success.hasOwnProperty("response.data.users.items.list")
This always evaluates to false because hasOwnProperty
cannot check multi-level objects apparently.
success.response.data.users.items.hasOwnProperty("list")
Error I got: TypeError: Cannot read property 'data' of undefined
Is there any modern and quick way of checking this?
Upvotes: 2
Views: 1298
Reputation: 9787
If it's an option for you, optional chaining is the way to go:
success?.response?.data?.users?.items?.list || {}
if not, you just have to check that each object exists before attempting to access a child property, or use ES6 destructuring with defaults (pretty gnarly with deeply-nested objects though):
const { response: { data: { users: { items: { list = {} } = {} } = {} } = {} } = {} } = success || {}
Upvotes: 6
Reputation: 491
If optional chaining is not an option, you could use something within those lines:
success && success.response && success.response.data &&
success.response.data.users && success.response.data.users.items && success.response.data.users.items.list
Upvotes: 2