I want to iterate over an array of objects but I get the parent object from a REST API service and sometimes the nested array of objects will be missing, for example:
var data = [
{
"post": {
"message": "this is a test",
"comments": [
{
"comment_text": "this is a comment"
}
]
}
}
]
If I wish to iterate over the comments, but have no guarantee that the post
or comment
object will be present, I currently pre-validate using:
if (data && data.post && data.post.comments) {
//iteration
}
Is there a cleaner way of doing the validation part?