Radical_Activity
Radical_Activity

Reputation: 2738

How to check if Object and its properties exist?

I receive an object from an API call. I want to check:

  1. If the object exists
  2. Whether the object's property has the property I'm looking for or not

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:

Is there any modern and quick way of checking this?

Upvotes: 2

Views: 1298

Answers (2)

Will Jenkins
Will Jenkins

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

Simon Kazakov
Simon Kazakov

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

Related Questions