0

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

1 Answer 1

3

In Typescript, you can use optional chaining...

this.addressEntryConfig?.addressModel?.partyMailingAddress?.address

It will only return the value of address if the rest of the properties are not null or undefined. If any are null or undefined, it will stop processing and just return undefined.

If other words you can do:

if (this.addressEntryConfig?.addressModel?.partyMailingAddress?.address)
    this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;

More on the TypeScript 3.7 release notes page here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

Sign up to request clarification or add additional context in comments.

4 Comments

cool, I thought this chaining feature comes out in ECMA 2020 release, is it already released? stackoverflow.com/a/2631198/12425844
If you are using Typescript you can already use it. In plain Javascript, though, optional chaining has not yet been added.
one more question, do I still need the If statement? could I just do this.addressMailingInputData = this.addressEntryConfig?.addressModel?.partyMailingAddress?.address;
Depends what you want to set this.addressMailingInputData to. If you don't use the if statement, it might be set to undefined. Which might be okay for what you're doing, but that's up for you to decide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.