只有当它真实时才能解构对象 [英] destructure object only if it's truthy

查看:70
本文介绍了只有当它真实时才能解构对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想像这样解构我的函数参数

Suppose I want to destructure my function argument like this

const func = ({field: {subField}}) => subField;

如果字段为 undefined,我如何防止此错误抛出 null

推荐答案

您可能会使用默认值:

const func = ({field: {subField} = {}}) => subField;

仅适用于 {field:undefined} 但是,不能将 null 作为值。为此,我只使用

It works only with {field: undefined} though, not with null as a value. For that I'd just use

const func = ({field}) => field == null ? null : field.subField;
// or if you don't care about getting both null or undefined respectively
const func = ({field}) => field && field.subField;

另见 javascript测试是否存在嵌套对象键以获得一般解决方案。

See also javascript test for existence of nested object key for general solutions.

这篇关于只有当它真实时才能解构对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆