简体   繁体   English

在Javascript中,如何检查嵌套在另一个键/值对中的特定键/值对的存在?

[英]In Javascript, how can I check the existence of a specific key/value pair nested inside another key/value pair?

For example, this is the value of the object I am processing: 例如,这是我正在处理的对象的值:

object = {"message":"success","dataList":{"state":"error","count":"25"}}

I know that to check if key "message" exists, I can do the following: 我知道要检查密钥“消息”是否存在,我可以执行以下操作:

if(object['message']){
    //"message" exists. do stuff.
} else{
    //"message" does not exist
}

How do I check for the existence of "state" or "count" though? 虽然如何检查“状态”或“计数”的存在?

if(object['dataList']['state']){
    // dataList["state"] exists. do stuff.
} else {
    // dataList["state"] does not exist
}

or the (in my opinion) more readable: 或者(在我看来)更具可读性:

if(object.dataList.state){ ... }

Edit : It would also be a good idea to check for all parent objects so you will not get an unexpected error when, for example, dataList does not exist on the object: 编辑 :检查所有父对象也是一个好主意,这样当对象上不存在dataList时,您不会收到意外错误:

if (object && object.dataList && object.dataList.state)

try like this: 试试这样:

object = {"message":"success","dataList":{"state":"error","count":"25"}};

    if(object.message =='success'){
        console.log(object.dataList);// your datalist object here use it
        console.log(object.dataList.state);
         console.log(object.dataList.count);
    } else{
        //"message" does not exist
    }

if you are trying to check state do this: 如果你想检查状态这样做:

if(typeof(object.dataList.state) !='undefined' && object.dataList.state.length > 0){
    // dataList.state exists. do stuff.
} else {
    // dataList.state does not exist
}

First of all, if you are checking the existence of a property, you should use if ('message' in object) . 首先,如果要检查属性的存在,则应使用if ('message' in object) If you use if (object['message']) , for the case object = {'message': null} , the result is wrong. 如果你使用if (object['message']) ,对于case object = {'message': null} ,结果是错误的。

In your question, the object is nested into two layers. 在您的问题中,对象嵌套在两个层中。 If there are more than two, you can try a generic solution using recursion: 如果有两个以上,您可以尝试使用递归的通用解决方案:

function findProperty (obj, key) {
    if (typeof obj === "object") {
        if (key in obj) return true;
        var childReturned = false;
        for (k in obj) {
            childReturned = findProperty(obj[k], key);
            if (childReturned) return true;
        }
    } 
    return false;
}

var obj = {"message":"success","dataList":{"state":"error","count":"25"}};
findProperty(obj, 'message');   // => true
findProperty(obj, 'dataList');  // => true
findProperty(obj, 'state');     // => true
findProperty(obj, 'count');     // => true
if (object.dataList.state || object.dataList.count) {
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM