I am getting hard time understanding this code , I looked through internet but still couldn't get it.
post.comments = post.comments.filter(
({ id }) => id !== req.params.comment_id
);
I want to know how this code is actually working.
I am getting hard time understanding this code , I looked through internet but still couldn't get it.
post.comments = post.comments.filter(
({ id }) => id !== req.params.comment_id
);
I want to know how this code is actually working.
.filter
is a function of Array
and it expects a callback function which returns a boolean value.
If the callback returns true
item will be added in returned array. For false
, it will be skipped.
() => {}
is called Arrow function, which is similar to an anonymous function but does not have context and its inherited from defining function.
({ id })
is a called as destructuring assignment where you can cherry-pick any property and create variable for it.
So the object comment
instide post.comments
will have id
property and you are just fetching it from object
Your code would look something like this in ES5
post.comments = post.comments.filter(function(comment) {
var id = comment.id;
return id !== req.params.comment_id;
})