Check if a key exists inside a JSON object Check if a key exists inside a JSON object json json

Check if a key exists inside a JSON object


Try this,

if(thisSession.hasOwnProperty('merchant_id')){}

the JS Object thisSession should be like

{amt: "10.00",email: "sam@gmail.com",merchant_id: "sam",mobileNo: "9874563210",orderID: "123456",passkey: "1234"}

you can find the details here


There's several ways to do it, depending on your intent.

thisSession.hasOwnProperty('merchant_id'); will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it.

thisSession["merchant_id"] will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false or the integer 0 and so on).


(I wanted to point this out even though I'm late to the party)
The original question you were trying to find a 'Not IN' essentially.It looks like is not supported from the research (2 links below) that I was doing.

So if you wanted to do a 'Not In':

("merchant_id" in x)true("merchant_id_NotInObject" in x)false 

I'd recommend just setting that expression == to what you're looking for

if (("merchant_id" in thisSession)==false){    // do nothing.}else {    alert("yeah");}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/inhttp://www.w3schools.com/jsref/jsref_operators.asp