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?
postsList[i].comments.lengthwithout the[j].