1

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.

hightides1973
  • 497
  • 1
  • 9
  • 27

5 Answers5

4

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,873
  • 3
  • 9
  • 16
3

You can use the nullish coalescing operator:

var gen = study["005"].Gen ?? "Unknown";
Miki
  • 1,625
  • 21
  • 29
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
  • 239
  • 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 – hightides1973 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,842
  • 2
  • 7
  • 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
  • 227
  • 1
  • 12