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');
findProperty(obj, 'dataList');
findProperty(obj, 'state');
findProperty(obj, 'count');
source
share