-2

I have a json object like below

let obj = { 'key1' : 'value1' , 'key2 : { 'key2a' : 'value2a' } }

I wanted to do a ternary operator check which is equivalent to below code

if(obj) {
  if(obj.key2) { 
    if(obj.key2.key2a) {
        return obj.key2a;
    }
  }
}

So, In google chrome console i have tried below to achieve it in simpler way and it worked...

obj?.key2?.key2a? obj.key2.key2a : '0'

enter image description here

If i am trying it in nodejs@12 its giving me syntax error.
enter image description here

Can someone please help me understand this discrepancy ?

Mr.Robot
  • 489
  • 2
  • 8
  • 17

1 Answers1

-1

I think you have a simple typo. You are checking this way

if(obj) {
  if(obj.key2) {  // <- obj.key2 here
    if(obj.key2a) { // <- but checking another property on the same level too
        return obj.key2a;
    }
  }
}

I think you mean

if(obj) {
  if(obj.key2) {  // <- obj.key2 here
    if(obj.key2.key2a) { // <- now safely access child property here
        return obj.key2.key2a;
    }
  }
}

or shorter

if (obj && obj.key2 && obj.key2.key2a) {
  // ...
}

or

var result = obj && obj.key2 && obj.key2.key2a || "0";
user2953241
  • 366
  • 2
  • 11