How would I check this javascript object?
{
"@": {
"xmlns": "http://ses.amazonaws.com/doc/2010-12-01/"
},
"SendEmailResult": {
"MessageId": "0000012fdd10caaf-021c6e9e-e872-4b35-ad94-1d11c79a6324-000000"
},
"ResponseMetadata": {
"RequestId": "736d5bb2-7b7d-11e0-b435-f7b0c9315f0d"
}
}
How do I check if "MessageId" exists in a object? (without throwing errors) I 开发者_Go百科might get other json objects returned, and I need to know if the one I get has a "MessageId".
Assuming you have a reference to it in obj
, then:
if (obj && obj.SendEmailResult && "MessageId" in obj.SendEmailResult) {
// The "MessageId" property exists in `obj.SendEmailResult`
}
Probably more usefully, though:
var msgid = obj && obj.SendEmailResult && obj.SendEmailResult.MessageId;
if (msgid) {
// The property exists and is "truthy", `msgid` is the value
}
JavaScript's AND operator &&
is more useful than that of some other languages, it returns the right-hand side's value if both of its operands are "truthy" (rather than just returning a true
/ false
result, as in most languages). A "truthy" value is a value that is not "falsy" (obviously). "Falsy" values are false
, undefined
, null
, ""
, and 0
.
So the above basically says "Set msgid
to obj.SendEmailResult.MessageId
provided that obj
and obj.SomeEmailResult
both exist.
(The ||
operator is similarly powerful.)
Assuming you get the result in a variable called result, you should be able to do this with a simple if statement (considering that the javascript if statement short circuits:
if (result && result["SendEmailResult"] && result["SendEmailResult"]["MessageId"]) {
//execute your code
}
精彩评论