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

  发布于 2023-02-07 19:37

试试这个,

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

}

JS对象thisSession应该是这样的

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

你可以在这里找到详细信息

5 个回答
  • 我会稍微更改您的if语句并起作用(也适用于继承的obj-在代码段中查看)

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

    if(!("merchant_id" in thisSession)) alert("yeah");
    
    2023-02-07 19:40 回答
  • 试试这个,

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

    JS对象thisSession应该是这样的

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

    你可以在这里找到详细信息

    2023-02-07 19:40 回答
  • 类型检查也可以:

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

    2023-02-07 19:40 回答
  • (即使我迟到了,我也想指出这一点)
    原来你试图找到一个'不在'的问题.看起来我从事的研究(下面的2个链接)不支持.

    所以,如果你想做一个'不在':

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

    我建议只将表达式==设置为您要查找的内容

    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

    2023-02-07 19:40 回答
  • 根据您的意图,有几种方法可以做到这一点.

    thisSession.hasOwnProperty('merchant_id'); 将告诉你thisSession本身是否具有该密钥(即它不是从其他地方继承的东西)

    "merchant_id" in thisSession 会告诉你thisSession是否有钥匙,无论它到底在哪里.

    thisSession["merchant_id"]如果密钥不存在,或者由于任何原因其值的计算结果为false,则返回false(例如,如果它是文字false或整数0,依此类推).

    2023-02-07 19:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有