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?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 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`. – anteAdamovic Nov 07 '17 at 11:14
  • 1
    Possible duplicate of [javascript test for existence of nested object key](https://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – JJJ Nov 07 '17 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 Nov 07 '17 at 11:15
  • You can check whether an object has a property written in [this answer](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript) – Ádám Révész Nov 07 '17 at 11:19

2 Answers2

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)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
-1

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

M.Tamil
  • 74
  • 4