When using two selects on a database, I am retrieving two arrays named "Movies" and "Comments". My goal is to merge these arrays based on their "movieId" and send the combined array back to the client in the response.
Movies:
[
{
"movieId": "0DD20C53-FF5C-EB11-8140-707781834352"
},
{
"movieId": "01C14AF4-3E37-EB11-8138-778184434310"
}
]
Comments:
[
{
"commentId": "1",
"movieId": "0DD20C53-FF5C-EB11-8140-707781834352",
"content": "thanks"
}
]
The desired outcome should look like this:
[
{
movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
comments: [
{
commentId: "1",
movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
content: "thanks",
}
]
},
{
movieId: "01D14A24-3E37-EB11-8118-778155534314",
comments: []
}
]
I have written the following code snippet, but there seems to be an issue as the comment is added to both movies. There might be an error with checking if the movie.movieId matches comment.movieId. Can someone guide me on how to correctly use .map and .filter or suggest a better solution for this scenario? Perhaps there is a more performance-efficient way.
let result = movies.map((movie) => ({
...movie,
comments: comments.filter((comment) => {
return comment.movieId === movie.movieId;
})
}));