检查密钥是否存在于json对象中

本文翻译自:Check if a key exists inside a json object

amt: "10.00"
email: "[email protected]"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"

The above is the JSON object I'm dealing with. 上面是我正在处理的JSON对象。 I want to check if the 'merchant_id' key exists. 我想检查'merchant_id'密钥是否存在。 I tried the below code, but it's not working. 我尝试了以下代码,但无法正常工作。 Any way to achieve it? 有办法实现吗?



#1楼

参考:https://stackoom.com/question/1PI71/检查密钥是否存在于json对象中


#2楼

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


#3楼

Try this, 尝试这个,

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

}

the JS Object thisSession should be like JS对象thisSession应该像

{
amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}

you can find the details here 您可以在这里找到详细信息


#4楼

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) 会告诉您thisSession是否具有该密钥本身(即不是它从其他地方继承来的)

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it. "merchant_id" in thisSession将告诉您thisSession是否完全具有密钥,无论它从何处获取。

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). 如果键不存在,或者键的值由于任何原因(例如,它是字面值false或整数0,依此类推),则thisSession["merchant_id"]将返回false。


#5楼

Type check also works : 类型检查也可以:

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

#6楼

(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. 您试图从本质上查找“ Not IN”的原始问题。 It looks like is not supported from the research (2 links below) that I was doing. 我正在做的研究似乎不支持(下面2个链接)。

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/in http://www.w3schools.com/jsref/jsref_operators.asp https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp

你可能感兴趣的:(javascript,json)