Reputation: 473
I get an object from parent component via props, the value of key2 can be undefined. Is it correct to use comparison like this?
const { myObject } = this.props
const canAdd = myObject.key1.key2 !== undefined
Upvotes: 0
Views: 42
Reputation: 3823
if key1
is not specified your code will throw an error, because key1
is not an object. You can assign defaults with object destructuring,
const { myObject: { key1: { key2 } = {} } = {} } = this.props
const canAdd = key2 !== undefined
This code is saying, go pull the prop myObject
out of this.props
if its not there assign it to an empty object, then go get me key key1
and if its not there assign it to be an empty object, inside key1
go grab the value key2
. If key2
is not a property on key1
, key2
will result in undefined.
Upvotes: 1