简体   繁体   English

是否可以在解构之前检查对象是否可用?

[英]Is it possible to check if the object is available before Destructuring?

I have an object of values to Destructure , But before doing so i would like to check if the object is available,我有一个要Destructure的值对象,但在这样做之前我想检查该对象是否可用,

const  { contactno, contactemail } =  this.props.app.user;

In this case the object user is not available always, Due to this I am getting following error,在这种情况下,对象user并不总是可用,因此我收到以下错误,

TypeError: Cannot read property 'contactno' of undefined.

Hence, Is there nay way to check if the object is available before Destructure ?因此,有没有办法在Destructure之前检查对象是否可用?

使用 AND 和 OR 运算符,您可以像这样安全地解构对象。

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) || {};

Use it like below (nested destructuring).像下面这样使用它(嵌套解构)。 If user is undefined the default to {} in destructuring.如果user undefined ,则解构时默认为{} when user is undefined, the contactno, contactemail also undefined with this.当用户未定义时,contactno、contactemail 也未定义。

const  { user: { contactno, contactemail } = {} } =  this.props.app;

你可以这样做

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) ? this.props.app.user : {} ;

You can also use the double question mark (nullish coalescing) operator您还可以使用双问号(空值合并)运算符

const { contactno, contactemail } = this.props.app.user ?? const { contactno, contactemail } = this.props.app.user ?? {}; {};

Reference: https://sebhastian.com/javascript-double-question-mark/参考: https ://sebhastian.com/javascript-double-question-mark/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM