gpt4 book ai didi

javascript - 我如何从javascript中的数组中删除嵌套对象或父对象

转载 作者:行者123 更新时间:2023-11-30 20:18:01 24 4
gpt4 key购买 nike

我想使用它的 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,我们将不胜感激。

最佳答案

您能检查一下这是否符合您的要求吗?

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") 这样进行初始调用

关于javascript - 我如何从javascript中的数组中删除嵌套对象或父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com