javascript - 使用唯一键更新 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"
}
}
}
}
解决方案
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))
推荐阅读
- ansible - 如何安装-t?
- html - HTML CSS:来自不同行的多个 DIV 的边框
- c# - 实体框架/表关系
- java - java 9中引入的方法是使用compiler target java 8编译的
- java - ZonedDateTime 以不同的值存储在数据库中,然后在代码中
- javascript - 源自数据 url (base64) 的音频标签在播放音频之前不会完全加载
- java - 如何在java项目中使用python
- web2py - 是否有 web2py 助手可以将新行转换为
? - python - Python 除以 10
- c++ - 当进程被分叉时,std::cin 没有阻塞