Check if a key exists inside a json object

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

The above is the JSON object I'm dealing with. I want to check if the 'merchant_id' key exists. I tried the below code, but it's not working. Any way to achieve it?

<script>
window.onload = function getApp()
{
  var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
  //console.log(thisSession);
  if (!("merchant_id" in thisSession)==0)
  {
    // do nothing.
  }
  else 
  {
    alert("yeah");
  }
}
</script>

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 (ie 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 (eg if it's a literal false or the integer 0 and so on).


类型检查也可以用作:

if(typeof Obj.property == "undefined"){
    // Assign value to the property here
    Obj.property = someValue;
}
链接地址: http://www.djcxy.com/p/26638.html

上一篇: 如何在JavaScript中创建哈希或字典对象

下一篇: 检查json对象内是否存在键