2

I have a javascript object called file, I am trying to check if this object has file.xhr.response property contained in it. I have tried like this..

if (file.xhr.response) {
    console.log(Exists);
} else {
    console.log(Missing);
}

This works when file.xhr.response exists but if it doesn't then it throws an error...

Uncaught TypeError: Cannot read property 'response' of undefined

Where am I going wrong?

4
  • When it throws Cannot read property 'response' of undefined it doesn't mean that response doesn't exist but rather then it's parent doesn't exist, in your case xhr. Commented Nov 7, 2017 at 11:14
  • 1
    Possible duplicate of javascript test for existence of nested object key
    – JJJ
    Commented Nov 7, 2017 at 11:14
  • The error says that response is not defined but the code you put in the question doesn't use response at all. The problem is not in the code you've shared.
    – Quentin
    Commented Nov 7, 2017 at 11:15
  • You can check whether an object has a property written in this answer Commented Nov 7, 2017 at 11:19

2 Answers 2

5

You can check if object property exists using:

if (file && file.xhr && file.xhr.response) {
    // your logic...
}

Code:

const a = {
  b: {
    d: 'd'
  }
}

const resultC = a && a.b && a.b.c ? 'Exists' : 'Missing';
console.log('a.b.c', resultC);

const resultD = a && a.b && a.b.d ? 'Exists' : 'Missing';
console.log('a.b.d', resultD);

But if you are dealing with a complex/bigger object you can recursively search for the property within the object

Code:

const a = {
  b: {
    d: {
      d: {
        e: {
          f1: {
            g: {
              h: 'h',
            }
          },
          f2: {
            g: {
              h: {
                i: 'i',
              },
            },
          },
        },
      },
    },
  },
}

const checkObjectProp = (o, p) => Object
  .keys(o)
  .some(k => k === p || (typeof o[k] === 'object' && checkObjectProp(o[k], p)))

const resultI = checkObjectProp(a, 'i') ? 'Exists' : 'Missing'
console.log(resultI)

-1

you can use something like if(typeof file.xhr!="undefined")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.