javascript - How to remove multi nested object in javascript using id
问题描述
Declaration of id
var id = 3;
I want to update this object
var obj = {"comments" : {
"commentedBy" : "test",
"date" : "",
"comment" : "Hello world",
"subComments" : {
"commentedBy" : "jaril 2",
"date" : "",
"comment" : "Hello world inside dark",
"subComments" : {
"commentedBy" : "jaril 3",
"date" : "",
"comment" : "wow working great",
"subComments" : {
"commentedBy" : "jaril 4",
"date" : "",
"comment" : "wow working great",
"commentId" : 4
},
"commentId" : 3
},
"commentId" : 2
},
"commentId" : 1
},
"dueDate" : "",
"createdDate" : "",
"lastUpdated" : "",
"checkList" : [],
"position" : 2,
"status" : "active"
}
}
Function is this
function deleteCommentId(comments){
if (comments.commentId == id)){
delete comments;
return comments;
}
if (comments.subComments) {
deleteCommentId(comments.subComments);
}
return comments;
}
Function Object is this
if(id == 1){
result[0].comments = {};
} else {
deleteCommentId(obj.comments);
}
console.log("final object==>", obj);
I want output like this
{"comments" : {
"commentedBy" : "test",
"date" : "",
"comment" : "Hello world",
"subComments" : {
"commentedBy" : "jaril 2",
"date" : "",
"comment" : "Hello world inside dark",
"commentId" : 2
},
"commentId" : 1
},
"dueDate" : "",
"createdDate" : "",
"lastUpdated" : "",
"checkList" : [],
"position" : 2,
"status" : "active"
}
}
Any help would be appreciated
Note: I want to remove nested subcomments object using id if I pass id=3 then it should remove subcomment of 2, How can I remove subcomments of 2 if id = 3
解决方案
下面的功能应该做到这一点。
(我删除了不相关的部分或您的对象,以使事情更容易阅读。)
var obj = {
"comments": {
"subComments": {
"subComments": {
"subComments": {
"commentId": 4
},
"commentId": 3
},
"commentId": 2
},
"commentId": 1
}
};
function deleteCommentId(comments, id) {
if (comments.subComments) {
if (comments.subComments.commentId === id) {
delete comments.subComments;
} else {
deleteCommentId(comments.subComments, id);
}
}
}
deleteCommentId(obj.comments, 3);
console.log(obj);
推荐阅读
- javascript - 如何播放 .wav 文件
- android - 使用像 gridview 这样的 Recyclerview
- java - 是否可以将元素添加到 SparseArray 的前面?
- python - 在不同的 Docker 容器中跨 Python 脚本的 IPC 共享内存
- javascript - Uncaught TypeError: $.get is not a function at
:1:3 - javascript - 我无法让我的 javascript 来切换我的登录下拉菜单。为什么javascript没有连接到我的html?
- ansible - ansible:如何将 selectattr 与 ipaddr 过滤器一起使用
- android - 未解决的参考:SavedStateVMFactory
- java - 在 AbstractTableModel 中使用 ResultSet 后 ResultSet 关闭后不允许操作
- ansible - AWX playbook 中的gather_facts 失败