0

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?

Or Weinberger
  • 7,332
  • 23
  • 71
  • 116

1 Answers1

0

One of the benefits of ImmutablsJS (outside it's core feature - immutability) is the nice API it exposes. If your data was an Immutable Map object you could iterate comments like this:

data.getIn(['post', 'comments'], List()).map(...)

notice that this code will work without any if statement, as you can pass an optional default result to getIn, in this case a empty List.

thedude
  • 9,388
  • 1
  • 29
  • 30