0

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!

Konrad
  • 21,590
  • 4
  • 28
  • 64

2 Answers2

2

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))
}
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • will using `hasOwn` be more helpful or is `hasOwnProperty` good in this case? –  Jan 27 '23 at 14:39
  • 1
    Use `Object.prototype.hasOwnProperty.call(obj, prop)` instead in case the object has [done something weird](https://stackoverflow.com/questions/12017693/why-use-object-prototype-hasownproperty-callmyobj-prop-instead-of-myobj-hasow) with its `hasOwnProperty` method. – kelsny Jan 27 '23 at 14:41
0

@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;
  }
 
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40