I need to access comment from posts array and based on the comment id I have to update the comment status. I can see the format of comment inside posts array as below:
{
id: ‘5fdcd812’,
title: ‘post1’,
comment: [ [ ‘c903c4dc’, ‘commentcontent’, ‘pending’ ] ]
}
Since comment is having two ‘[‘ brackets when I search for comment.id it is showing as undefined.
So please help me here, how can I access the comment Id
Here is my code snippet:
app.post('/events',(req,res)=>{ const {type,data} = req.body; if(type === 'postCreated'){ const {id,title} = data; posts[id] = {id,title,comment:[]} } if(type === 'CommentCreated'){ const {id,content,postId,status} = data; const post = posts[postId]; post.comment.push([id,content,status]); } if(type === 'CommentUpdated'){ const {id,content,postId,status} = data; const post = posts[postId]; const comments = post.comment.find(comm=>{ return comm.id===id }); console.log(comments); comments.status = status; comments.content = content; } res.send({}); })
Advertisement
Answer
Instead of nested arrays
post.comment.push([ id, content, status]);
it might make more sense to add that data as an object
post.comment.push({ id, content, status });
That way you could access the comments by their keys rather than array indexes. Which looks like what you’re trying to do.
const data = { id: '5fdcd812', title: 'post1', comments: [ { id: 'c903c4da', content: 'commentcontent', status: 'success' }, { id: 'c903c4dc', content: 'commentcontent', status: 'pending' } ] }; const id = 'c903c4da'; const comment = data.comments.find(comment => comment.id === id); console.log(comment);