检查一个JSON对象内是否存在一个键

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> 

尝试这个,

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

JS对象thisSession应该是这样的

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

你可以在这里find细节

有几种方法可以做到这一点,这取决于你的意图。

thisSession.hasOwnProperty('merchant_id'); 会告诉你,这个会话本身是否有这个密钥(即不是从别处inheritance的东西)

"merchant_id" in thisSession会告诉你这个会话是否有密钥,而不pipe它在哪里。

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

types检查也将作为:

 if(typeof Obj.property == "undefined"){ // Assign value to the property here Obj.property = someValue; } 

即使我迟到了,我只想指出这一点。 原来的问题,你试图find一个“不在”本质上看起来像是不支持研究(2链接下面),我正在做的。 所以如果你想做一个不是:

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

我build议只是将expression式==设置为你要找的

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

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

函数来检查未定义和空对象

 function elementCheck(objarray, callback) { var list_undefined = ""; async.forEachOf(objarray, function (item, key, next_key) { console.log("item----->", item); console.log("key----->", key); if (item == undefined || item == '') { list_undefined = list_undefined + "" + key + "!! "; next_key(null); } else { next_key(null); } }, function (next_key) { callback(list_undefined); }) } 

这里是一个简单的方法来检查发送的对象是否包含undefined或null

 var objarray={ "passenger_id":"59b64a2ad328b62e41f9050d", "started_ride":"1", "bus_id":"59b8f920e6f7b87b855393ca", "route_id":"59b1333c36a6c342e132f5d5", "start_location":"", "stop_location":"" } elementCheck(objarray,function(list){ console.log("list"); ) 

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