Using two selects to database I'm returning two arrays "Movies" and "Comments" and I must to merge this arrays based on "movieId" into one and send it back to client in 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"
},
]
And in that case I want this result:
[
{
movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
comments: [
{
commentId: "1",
movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
content: "thanks",
},
],
},
{
movieId: "01C14AF4-3E37-EB11-8138-778184434310",
comments: [],
},
];
Currently I wrote this code, but something is wrong because comment is added to both movies so something is wrong with checking movie.movieId = comment.movieId. Can someone tell me how to use .map and .filter correctly or better solution to that case? Maybe there is something better for performance.
let result = movies.map((movie) => ({
...movie,
comments: comments.filter((comment) => {
comment.movieId = movie.movieId;
}),
}));