1

I have trouble understanding nested for loops

posts: [
  {
    title: 'lorem',
    comments: [
      {
         content: 'lorem'
         user: 'John'
      },
      ...
    ]
  },

  ...
]

My goal here is to get all the comments from a specific user, in all the posts. Here is how I proceed (I'm using mongoose, I get the user from an auth middleware)

const postsList = await Post.find();
var userComments = [];

 for (var i = 0; i < postsList.length; i++) {

     if (postsList[i].comments.length > 0) {

        for (var j = 0; j < postsList[i].comments[j].length; i++)

          if (postsList[i].comments[j].user == req.user.id) {
            userComments.push(comments[j]);
          }
      }
 }

When I try this, I get a Cannot read property 'length' of undefined. I think my error is in the second for loop, but I can't get why. Any help please?

1
  • 1
    It should probably be postsList[i].comments.length without the [j]. Commented Jun 23, 2019 at 15:13

1 Answer 1

3

Mark Meyer in the comments is correct.

comments is an array inside of each post object. comments[j] would refer to an element inside the comments array. comments[j].length doesn't make sense because in order to run your nested j for loop, which iterates over the comments array, you want the length of the comments array, not the length of one of its elements.

Here's the line that needs to be fixed:

const postsList = await Post.find();
var userComments = [];

 for (var i = 0; i < postsList.length; i++) {

     if (postsList[i].comments.length > 0) {

       // for (var j = 0; j < postsList[i].comments[j].length; i++)
       // fixed version below
        for (var j = 0; j < postsList[i].comments.length; i++)


          if (postsList[i].comments[j].user == req.user.id) {
            userComments.push(comments[j]);
          }
      }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.