2

Imagine this code:

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj.a.b) {
  //fail because "cannot read property 'b' of undefined
}

The question is : How I can check the existence of a "leave" (if "b" exist, it must inside "a") without making the test of each its parents before ?

coutier eric
  • 949
  • 5
  • 18

3 Answers3

0

Use to check if key exist or not.

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

function isExist(arg){
   try{
      return arg();
   }catch(e){
      return false;
   }
}

console.log(isExist(()=>obj.x.y))
console.log(isExist(()=>obj.x.y.z))
console.log(isExist(()=>obj.a.b))

Reference : Test for existence of nested JavaScript object key

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
0

You can use elvis operator.

if (obj.a?.b) { // no error thrown
  console.log('error'); // 'error' isn't be logged
}
vadimk7
  • 6,559
  • 1
  • 12
  • 15
0

There is a proposal in the works for an operator that looks like ?. called optional chaining

You would then use it on your example like

obj.a?.b

For now though, you'll have to write more to safely access nested properties

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj && obj.a && obj.a.b) {
  // will not throw
} else {
  console.log('didn\'t throw!')
}
richytong
  • 2,387
  • 1
  • 10
  • 21