如何使用ID在JavaScript中删除多嵌套对象

时间:2018-08-03 08:49:24

标签: javascript object

  

ID声明

var id = 3;
  

我要更新该对象

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 deleteCommentId(comments){
  if (comments.commentId == id)){
    delete comments;
    return comments;
  }
  if (comments.subComments) {
    deleteCommentId(comments.subComments);
  } 
  return comments;
}
  

功能对象是这个

if(id == 1){
    result[0].comments = {};
} else {
    deleteCommentId(obj.comments);
}
console.log("final object==>", obj);
  

我想要这样的输出

          {"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"
        }
      }
  

任何帮助将不胜感激

     

注意:如果我通过,我想使用id删除嵌套的子注释对象    id = 3那么它应该删除2的子注释,如果id = 3,如何删除2的子注释

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

Array.filter()