javascript - Check nested JSON in Javascript/Typescript to see if Data is null before operation
问题描述
Is there an easier way in Typescript/Javascript to check if nested JSON object is null, and then set a value? Right now, we have to peruse through 4 data layers to check if they are null, and then we can conduct operation to set value. Curious if there is any easier syntax?
if (this.addressEntryConfig
&& this.addressEntryConfig.addressModel
&& this.addressEntryConfig.addressModel.partyMailingAddress
&& this.addressEntryConfig.addressModel.partyMailingAddress.address) {
this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;
}
Resource: Test for existence of nested JavaScript object key
解决方案
在 Typescript 中,您可以使用可选链...
this.addressEntryConfig?.addressModel?.partyMailingAddress?.address
如果其余属性不为空或未定义,它将仅返回地址的值。如果任何一个为空或未定义,它将停止处理并返回未定义。
如果换句话,你可以这样做:
if (this.addressEntryConfig?.addressModel?.partyMailingAddress?.address)
this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;
有关 TypeScript 3.7 发行说明页面的更多信息:https ://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
推荐阅读
- r - 调试模式后变量未出现在 RStudio 全局环境中
- javascript - 通过 javascript 显示的 SVG 绘图不显示
- c# - 当你获得一定的分数时,如何在 C# 中添加新的玩家生活?
- c# - 如何获取在不同 AppDomain 中加载的 ac# 程序集的内存基地址
- php - Moodle 错误:检测到数据库驱动程序问题
- kuzzle - Kuzzle:执行此操作的权限不足
- javascript - 过滤低值余额并隐藏空复选框
- geometry - 不能从空值创建匀称的几何图形
- python - 从 py 文件中使用 scrapy(不在命令行中)
- css - 如何将多个内联样式作为道具应用到组件?