简体   繁体   English

仅当嵌套 object 具有值时,如何解构它?

[英]How to destructure a nested object only when it has a value?

  let notStudent, name, isRegistered
  if (studentDetail && studentDetail.fields) {
    ({ notStudent, name, isRegistered } = studentDetail.fields)
  }

Is there a way to write this logic without an if statement or in a succinct way?有没有办法在没有 if 语句的情况下或以简洁的方式编写此逻辑?

You can destructure in this way.你可以用这种方式解构。 The tricky thing is when there is no fields property on studentDetail then javascript can throw an error, to tackle that case, you can set default empty object using ||棘手的是,当 studentDetail 上没有 fields 属性时,javascript 会抛出错误,为了解决这种情况,您可以使用 || 设置默认的空 object operator.操作员。

 let studentDetail = { fields: { notStudent: '1', name: '2', isRegistered: true } } let { notStudent, name, isRegistered } = (studentDetail && studentDetail.fields) || {}; console.log(notStudent); console.log(name); console.log(isRegistered);

You can destructure an empty default object in case your studentDetail.fields doesn't exist:如果您的studentDetail.fields不存在,您可以解构一个空的默认 object:

const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};

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

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