s_kamianiok
s_kamianiok

Reputation: 473

Is it correct to compare unused key in object with undefined?

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

Answers (1)

Dan Starns
Dan Starns

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

Related Questions