如何从JavaScript中的数组中删除嵌套对象或父对象

时间:2018-08-07 09:19:26

标签: javascript object

我想使用其ID删除对象,我不希望MongoDB查询我 只想使用其ID,存储在变量中的数组删除对象, 我们也可以使用javascript函数

示例
如果我从该对象传递id=ObjectId("5b693e7ddd65ec16a46b7f82")

 [{
     "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")
 }]

然后输出应该是这样

[]

或者如果我通过id=ObjectId("5b693e7ddd65ec16a46b7f83"),则输出应该如此

[{
    "commentedBy": "test",
    "commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]

我使用此递归函数删除注释,但并没有删除,因为我们需要传递它的密钥

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))
})

如果我有500个子评论,那么我们应该可以 它的ID,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

能否请您检查一下是否满足您的要求?

function retComment(commentArray, id) {
    if (commentArray.commentId === id || !commentArray.subComments) {
        return [];
    } else if (commentArray.subComments && commentArray.subComments.commentId === id) {
        return {
            "commentedBy": commentArray.commentedBy,
            "commentId": commentArray.commentId
        }
    } else {
        retComment(commentArray.subComments, id)
    }
}

您需要像retComment(commentArray[0], "5b693e7ddd65ec16a46b7f82")那样拨打电话