Home > Enterprise >  Recursive hasOwnProperty for objects
Recursive hasOwnProperty for objects

Time:01-28

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!

CodePudding user response:

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))
}

CodePudding user response:

@MisterJojo I am trying to assigning a value

so you may do that this way...

const 
  objA = {}
, objB = { propX: 'b' } 
, objC = { propX: { propX: 'c' } }
  ;
setLastProp( objA, 'propX', 'x_A' );
setLastProp( objB, 'propX', 'x_B' );
setLastProp( objC, 'propX', 'x_C' );

console.log( 'objA ->', JSON.stringify( objA ));
console.log( 'objB ->', JSON.stringify( objB ));
console.log( 'objC ->', JSON.stringify( objC ));



function setLastProp  ( obj, propName, value )
  {
  let next = obj, prev = obj, count = 0;
  while (next.hasOwnProperty(propName)) 
    {  
    prev = next;
    next = next[propName];
    };
  prev[propName] = value;
  }
 

  • Related