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
  • 889
  • 5
  • 16
  • Check my answer this way you no need to figure what leave and parent are there. you can figure out passing params. – aviboy2006 May 30 '20 at 19:25

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

aviboy2006
  • 7,334
  • 5
  • 24
  • 43
0

You can use elvis operator.

if (obj.a?.b) { // no error thrown
  console.log('error'); // 'error' isn't be logged
}
vadimk7
  • 3,389
  • 1
  • 11
  • 14
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,302
  • 9
  • 18