首页 > 解决方案 > 使用唯一键更新 Javascript 对象嵌套值

问题描述

我想id在每个子评论中添加唯一的,评论可能超过 100,我得到这个对象作为输入,我必须添加自动增量并插入数据库,任何帮助将不胜感激。

我想更新这个object

var objData =   {"comments":{
        "commentedBy" : "jaril1",
        "date" : "",
        "comment" : "Hello world",
        "subComments" : {
            "commentedBy" : "jaril 2",
            "date" : "",
            "comment" : "Hello world inside dark",
            "subComments" :{
                "commentedBy": "jaril 3",
                "date": "",
                "comment": "wow working great"
            }
        }
    }
}

对此:

var objData =   {"comments":{
        "commentId":1,
        "commentedBy" : "jaril1",
        "date" : "",
        "comment" : "Hello world",
        "subComments" : {
            "commentId":2,
            "commentedBy" : "jaril 2",
            "date" : "",
            "comment" : "Hello world inside dark",
            "subComments" :{
                "commentId":3,
                "commentedBy": "jaril 3",
                "date": "",
                "comment": "wow working great"
            }
        }
    }
}

标签: javascript

解决方案


var objData = {"comments":{"commentedBy":"jaril1","date":"","comment":"Hello world","subComments":{"commentedBy":"jaril 2","date":"","comment":"Hello world inside dark","subComments":{"commentedBy":"jaril 3","date":"","comment":"wow working great"}}}}

var id=1
function updateComment(commenObj){
  return commenObj.subComments ? {...commenObj, commentId: id++, subComments: updateComment(commenObj.subComments)} : {...commenObj, commentId: id++}
}

console.log(updateComment(objData.comments))


推荐阅读