Search code examples
javascriptecmascript-6ecmascript-5

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:

  • 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?


Solution

  • 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 || {}