Search code examples
javascripttypescriptundefinedhasownproperty

Recursive hasOwnProperty for objects


I have an object as:

const object = {};
object.property1 = 54;
object.property1.property1 = 60;

now I would like to achieve something like this:

if(object.hasOwnProperty('property1')){
//do something
}
else if(object.hasOwnProperty('property1').hasOwnProperty('property1')){
//do something
}
else{
//do something
}

But it fails at the else if part. why can't we use hasOwnProperty recursively? what is the workaround? I am stuck at this for many hours now.

I have tried to use:

if(object.property1.property1){
//do something
}

but this gives me undefined

So how to get around this situation? Please help!


Solution

  • I would use a recursive function

    const object = {};
    object.property1 = {};
    object.property1.property2 = 60;
    
    if (hasOwnPropertyRecursive(object, 'property2')) {
      console.log('yes')
    } else {
      console.log('no')
    }
    
    function hasOwnPropertyRecursive(obj, prop) {
      if (typeof obj !== 'object' || obj === null) return false
      if (obj.hasOwnProperty(prop)) return true
      return Object.getOwnPropertyNames(obj).some(key => hasOwnPropertyRecursive(obj[key], prop))
    }