首页 > 解决方案 > 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

标签: javascriptangulartypescriptangular8

解决方案


在 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


推荐阅读