0

I am trying to check if key ("Gen") exists and if exists return the value itself if not return "Unknown".

my object looks like this.

study = {
  "005": 
     {

        "Gen" : ["F"],
        "vr" : "cs"
      }
}
study = {
  "005": 
      {
        "vr" : "cs"
      }
}

in function i am trying to return the value of "Gen"

var gen = study["005"].Gen !== "undefined" || study["005"].Gen !== null ? study["005"].Gen[0] : "Unknown";

but here it throws me an error as in second case : where "Gen" doesn't exist but still it passes the if condition and looks for study["005"].Gen[0]

how to check if the "Gen" exists!! Any help appreciated.

user28
  • 467
  • 1
  • 8
  • 20

5 Answers5

3

You can use the nullish coalescing operator:

var gen = study["005"].Gen ?? "Unknown";
Miki
  • 1,203
  • 17
  • 26
2

Standard function style here for your reference. You should use .hasOwnProperty

study = {
  "005": {     
        "Gen" : ["F"],
        "vr" : "cs"      
   },
}
let gen;
function check() {
  if (study["005"].hasOwnProperty("Gen")) {
    gen = study["005"]["Gen"]
  } else
    gen = "Unknown"
}
check()
console.log(gen)

And what you want

var gen = study["005"].hasOwnProperty("Gen") ? study["005"]["Gen"] : "Unknown" ;
Justin
  • 2,653
  • 3
  • 5
  • 14
  • it works :) thank you..mistake i did was : checking the condition itself and then accessing the value of "Gen". – user28 May 17 '21 at 03:43
0

You'd have to change it to

var gen = study["005"].Gen !== undefined ? study["005"].Gen[0] : "Unknown" ;

Additionally, you have an extra pair of curly brackets. Instead of

study = {
  "005": {
      {
        "Gen" : ["F"],
        "vr" : "cs"
      }
   },
}
study = {
  "005": {
      {
        "vr" : "cs"
      }
   }
}

it should be

study = {
  "005": {
      "Gen" : ["F"],
      "vr" : "cs"
   },
}
study = {
  "005": {
      "vr" : "cs"
   },
}
Kyruski
  • 229
  • 1
  • 9
  • yes you are right..i had by mistake added extra pair of curly brackets.. but corrected it now. meanwhile i tried the code which you said but i get the error in console.. var gen = study["005"].Gen !== undefined ? study["005"].Gen[0] : "Unknown" ; Uncaught TypeError: Cannot read property '0' of undefined – user28 May 17 '21 at 03:38
0

The correct condition to check for the key will be: study["005"].Gen !== undefined && study["005"].Gen !== null ? study["005"].Gen[0] : "Unknown";

Yash Maheshwari
  • 1,631
  • 2
  • 6
  • 16
0

I think the data is invalid as well, so I tried cleaning it up a little. Does the following work for you?

const study = {
    "005":
    {
        "Gen": ["F"], "vr": "cs"
    }

}

if(JSON.stringify(study['005']).includes('Gen')) {
    console.log(study['005']['Gen']);
}
Fisk
  • 195
  • 9