In Javascript, how can I check for a specific key / value pair nested inside another key / value pair?

For example, this is the value of the object that I am processing:

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

I know that to check for the presence of a message key, I can do the following:

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

How to check for a “status" or "account" though?

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

or (in my opinion) are more readable:

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

Change . It would also be nice to check all the parent objects so that you do not receive an unexpected error if, for example, it dataListdoes not exist on the object:

if (object && object.dataList && object.dataList.state)
+3
source

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(typeof(object.dataList.state) !='undefined' && object.dataList.state.length > 0){
    // dataList.state exists. do stuff.
} else {
    // dataList.state does not exist
}
0

First of all, if you are checking for the existence of a property, you should use if ('message' in object). If you use if (object['message']), for the case object = {'message': null}, the result is incorrect.

In your question, the object is nested in two layers. If there are more than two, you can try a general 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
0
source
if (object.dataList.state || object.dataList.count) {
    // ...
}
0
source

All Articles