Check if a key exists inside a json object

后端 未结 9 1346
旧巷少年郎
旧巷少年郎 2020-11-29 14:48
amt: \"10.00\"
email: \"sam@gmail.com\"
merchant_id: \"sam\"
mobileNo: \"9874563210\"
orderID: \"123456\"
passkey: \"1234\"

The above is the JSON o

相关标签:
9条回答
  • 2020-11-29 15:44

    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

    0 讨论(0)
  • 2020-11-29 15:46

    You can try if(typeof object !== 'undefined')

    0 讨论(0)
  • 2020-11-29 15:49

    I change your if statement slightly and works (also for inherited obj - look on snippet)

    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");

    0 讨论(0)
提交回复
热议问题