I am looking for a way to remove an object based on its id without using a MongoDB query. Instead, I want to remove the object from an array stored in a variable using a JavaScript function.
For example, if I provide
id=ObjectId("5b693e7ddd65ec16a46b7f82")
from this object:
[{
"commentedBy": "test",
"subComments": {
"commentedBy": "jaril 2",
"subComments": {
"commentedBy": "jaril 3",
"subComments": {
"commentedBy": "jaril 4",
"commentId": ObjectId("5b693e7ddd65ec16a46b7f85")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f84")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f83")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]
the expected output should be an empty array.
[]
Alternatively, if I pass
id=ObjectId("5b693e7ddd65ec16a46b7f83")
, then the output should look like this:
[{
"commentedBy": "test",
"commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]
I have tried using a recursive function to remove comments but it's not working as expected because we need to pass the key of the comment along with the id.
async.eachSeries(result[0].comments, function (data, cb) {
function deleteCommentId(comments) {
if (comments.commentId.valueOf() == req.body.commentId) {
delete comments
}
if (comments.subComments) {
deleteCommentId(comments.subComments);
}
return comments;
}
deleteCommentId(data)
return cb();
}, function () {
console.log(JSON.stringify(resultFind))
})
If there are 500 sub comments, we should be able to remove any of them based on their ids. Any help or guidance would be greatly appreciated.