0

I have a posts array with comments and replies. I am trying to filter all replies where body contains 'first comment' and also select all the replies where post_id = 1 but I'm getting an error.

P.S. I don't know the index.

error: Uncaught TypeError: Cannot read property 'body' of undefined

Here is the posts array.

let posts = [
  {
    id: 1,
    body: 'First post',
    comments: [
      {
        id: 1,
        body: 'First post comment',
        post_id: 1,
        replies: [
          {
            id: 1,
            post_id: 1,
            comment_id: 1,
            body: 'Reply to first comment of first post'
          }
        ]
      }
    ]
  }
]

I tried it like this but it is giving me errors:

/**
 * error: Uncaught TypeError: Cannot read property 'body' of undefined
 */
let first_comment = posts.map(item => {
  return item.comments.replies.body.contains('first comment')
})


/**
 * error: Uncaught TypeError: Cannot read property 'post_id' of undefined
 */
let first_post_comments = posts.map(item => {
  return item.comments.replies.post_id === 1
})
Liga
  • 3,291
  • 5
  • 34
  • 59
  • 1
    Well, `item.comments` is another array; it doesn’t have a `replies` property. You need to iterate over that. – Sebastian Simon Oct 15 '19 at 06:16
  • comments is an array. so you can't access comments.replies – Sudhakar Oct 15 '19 at 06:16
  • 1
    `item.comments` is an array which doesn't have a property `replies` so it can not be read `body` of something that is not defined: the message is clear about that: `item.comments.replies` is _`undefined`_. – lealceldeiro Oct 15 '19 at 06:17
  • How can I iterate over each sub array to find the value I'm looking for? – Liga Oct 15 '19 at 06:40

0 Answers0