1

I have the following object called this.props:

{
  children: null,
  location: {
    action: 'POP',
    query: {
      seconds: '300'
    }
  }
}

After looking at this question I wrote the following code:

let seconds = 0;

console.log(this.props);

if('seconds' in this.props) {
 seconds = parseInt(this.props.location.query.seconds, 10);
}

console.log(seconds);

In the console the object is logged as above, but seconds is logged as 0.

I do not understand what is wrong with my if check, it seems that the condition is failing even though the nested object has the correct property (the issue is that when there is no query object, the whole this.props object is empty - so I need to check for nested properties).

Community
  • 1
  • 1
Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163

1 Answers1

1

Seconds is not in this.props; it's on query. The in operator is not recursive, just first level:

if('seconds' in this.props.location.query) {
 seconds = parseInt(this.props.location.query.seconds, 10);
}

console.log(seconds); // 300

If you want to do it recursively, create your own function:

let isIn = function (obj, key) {
  return isObj(obj) ? (key in obj) || Object.values(obj).filter(f => isIn(f, key)).length > 0 : false;
}

Where isObj is a function that verifies if the parameter is an object. You can use lodash or equiv., or make something like:

let isObj = t => (t !== null) && (typeof t === 'object');
Luan Nico
  • 5,376
  • 2
  • 30
  • 60