Home > Software engineering >  How to use string template while using JSON?
How to use string template while using JSON?

Time:10-12

I am working on a project and would like to use prodConfig or draftConfig according to few conditions. I am using Hasura and getting 2 different JSON responses with only 1 key different in the response i.e.prodConfig or draftConfig

Example:

data.businesses_by_pk.draftConfig or data.businesses_by_pk.prodConfig

So, I thought of using a string template ( ${} ) but that doesn't work:

Hence, I tried this:

let configFile = Object.keys(data.businesses_by_pk)[1]; //This gives either 'prodConfig' or 'draftConfig'
let header = data.businesses_by_pk.configFile;

But this returns undefined.

Please help me with this. Correct me If I am wrong somewhere, I am new to this.

CodePudding user response:

let header = data?.businesses_by_pk?.draftConfig || data?.businesses_by_pk?.prodConfig

You can use optional chaining to dig into the object. It won't error out, it will instead return undefined. You can then set a default when it does return undefined.

For example: let names = (data?.name || data?.firstName) ?? 'smith' Where smith will be the default if any of the names beforehand is falsy

  • Related