繁体   English   中英

JavaScript 对象内部的嵌套解构

[英]Nested Destructuring in JavaScript Inside Objects

我需要在我的 React 应用程序的嵌套对象中声明orderItems 有时order为空,因此找不到orderItems 所以错误当然是Cannot read property of orderItems of null 我该如何解决?

 const { order: { orderItems = [] } = {} } = res.cartFind

有时 order 为空,因此找不到 orderItems。

因为它是null (不是undefined ),所以我们不能用默认值解决它(因为它们只适用于缺少或undefined东西,特别是)。 但由于它位于res.cartFind的顶层,我们可以使用nullish 合并来解决它。 删除{order: ....}部分并将.order移动到最后,然后默认为?? {} ?? {} ,并解构:

const { orderItems = [] } = res.cartFind.order ?? {};

现场示例:

 function example(res) { const { orderItems = [] } = res.cartFind.order ?? {}; console.log(orderItems); } console.log("When order is null:"); example({ cartFind: { order: null, }, }); console.log("When order is not null:"); example({ cartFind: { order: { orderItems: [1, 2, 3], }, }, });

在评论中,我想你已经问过如果order在那里并且它有orderItems: null会怎样。 有了上面的内容,您最终会得到null ,因为(再次)默认值仅在缺少某些内容或undefined时才会使用。

处理undefinednull (我们称之为“nullish”值)的两个东西是 nullish 合并(我们在上面使用过), ?? , 和可选的链接, ?. .

如果order可能丢失,或者它可能存在但其中orderItems: null ,您可以使用两者的组合来处理它:

const orderItems = res.cartFind.order?.orderItems ?? [];

这是它的工作原理:

  1. 如果res.cartFind.ordernullundefined (或缺失,实际上是undefined ),则res.cartFind.order?.orderItems导致undefined (它不会像没有? order后)。 如果res.cartFind.order不是nullundefined (nullish),那么我们尝试从中获取orderItems
  2. 所以现在res.cartFind.order?.orderItems已经被评估并给了我们undefinedorderItems的值(可能是任何东西)。 通过使用thatResultValue ?? [] thatResultValue ?? []我们说“如果它不是nullundefined ,则使用thatResultValue ,但如果是,则使用[] 。”

现场示例:

 function example(res) { const orderItems = res.cartFind.order?.orderItems ?? []; console.log(orderItems); } console.log("When order is null:"); example({ cartFind: { order: null, }, }); console.log("When order is not null and has a valid orderItems:"); example({ cartFind: { order: { orderItems: [1, 2, 3], }, }, }); console.log("When order is not null but doesn't have orderItems:"); example({ cartFind: { order: { }, }, }); console.log("When order is not null and has orderItems but it's null:"); example({ cartFind: { order: { orderItems: null, }, }, });
 .as-console-wrapper { max-height: 100% !important; }

暂无
暂无

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

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