Skip to content
Advertisement

Javascript object check if property exists

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?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement