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 Answers1

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

Kurt
  • 1,868
  • 3
  • 21
  • 42
  • cool, I thought this chaining feature comes out in ECMA 2020 release, is it already released? https://stackoverflow.com/a/2631198/12425844 –  Feb 17 '20 at 01:12
  • 1
    If you are using Typescript you can already use it. In plain Javascript, though, optional chaining has not yet been added. – Kurt Feb 17 '20 at 01:15
  • one more question, do I still need the If statement? could I just do this.addressMailingInputData = this.addressEntryConfig?.addressModel?.partyMailingAddress?.address; –  Feb 17 '20 at 17:41
  • 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. – Kurt Feb 17 '20 at 19:42