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

以上就是我要处理的JSON对象。我想检查merchant_id键是否存在。我尝试了下面的代码,但它不工作。有办法实现吗?

<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>

当前回答

根据你的意图,有几种方法可以做到这一点。

thisSession.hasOwnProperty(“merchant_id”);会告诉你这个session本身是否有这个键(即不是它从其他地方继承的东西)

"merchant_id"在thisSession将告诉你这个session是否有密钥,不管它从哪里得到它。

thisSession["merchant_id"]将返回false如果键不存在,或者如果它的值因任何原因计算为false(例如,如果它是一个字面值false或整数0等等)。

其他回答

我稍微改变你的if语句和工作(也为继承的obj -看片段)

if(!("merchant_id" in thisSession)) alert("yeah");

var sessionA = { amt: "10.00", email: "sam@gmail.com", merchant_id: "sam", mobileNo: "9874563210", orderID: "123456", passkey: "1234", } var sessionB = { amt: "10.00", email: "sam@gmail.com", mobileNo: "9874563210", orderID: "123456", passkey: "1234", } var sessionCfromA = Object.create(sessionA); // inheritance sessionCfromA.name = 'john'; if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA"); if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB"); if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA"); if ("merchant_id" in sessionA) alert("merchant_id in sessionA"); if ("merchant_id" in sessionB) alert("merchant_id in sessionB"); if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");

你可以试试if(typeof object !== 'undefined')

根据你的意图,有几种方法可以做到这一点。

thisSession.hasOwnProperty(“merchant_id”);会告诉你这个session本身是否有这个键(即不是它从其他地方继承的东西)

"merchant_id"在thisSession将告诉你这个session是否有密钥,不管它从哪里得到它。

thisSession["merchant_id"]将返回false如果键不存在,或者如果它的值因任何原因计算为false(例如,如果它是一个字面值false或整数0等等)。

你可以这样做:

if("merchant_id" in thisSession){ /** will return true if exist */
 console.log('Exist!');
}

or

if(thisSession["merchant_id"]){ /** will return its value if exist */
 console.log('Exist!');
}

试试这个,

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

}

JS对象thisSession应该像这样

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

你可以在这里找到细节