Javascript 遍历每个嵌套对象并为每个对象创建一个div

Javascript 遍历每个嵌套对象并为每个对象创建一个div,javascript,node.js,recursion,data-structures,ejs,Javascript,Node.js,Recursion,Data Structures,Ejs,使用以下对象,我需要使用EJS为该数组中的每个obj创建一个htmldiv元素 div应该是这样的: <div> <div>Original comment</div> <div>The replies of that original comment</div> <div>The replies of the replies etc</div> </div> 感谢您抽出时间

使用以下对象,我需要使用EJS为该数组中的每个obj创建一个htmldiv元素

div应该是这样的:

<div>
    <div>Original comment</div>
    <div>The replies of that original comment</div>
    <div>The replies of the replies etc</div>
</div>
感谢您抽出时间

您可以用

如果您还没有它,您可能需要在您的环境中多填充它

Array.prototype.flatMap = function (f)
{
  return this.reduce ((acc, x) => acc.concat (f (x)), [])
}
程序演示

让obj=[
{
“id”:1,“评论”:“第一次更新的评论”,“parentID”:null,“回复”:[{
“id”:5,“评论”:“这是对评论id 1的回复”,“家长id”:1,“回复”:
[{“id”:9,“评论”:“回复id 5”,“家长id”:5,“回复”:[]}]
}]
},
{“id”:2,“comment”:“Second comment”,“parentID”:null,“replements”:[]},
{“id”:3,“评论”:“第三条评论”,“parentID”:null,“回复”:[]},
{“id”:4,“评论”:“第四条评论”,“parentID”:null,“回复”:[{“id”:6,“评论”:“回复评论id 4”,“parentID”:4,“回复”:[]}],
{“id”:7,“注释”:“测试黑色”,“parentID”:null,“回复”:[]},
{“id”:8,“comment”:“TriHard 7 comment id 7”,“parentID”:null,“represponses”:[]}
];
Array.prototype.flatMap=函数(f)
{
返回此.reduce((acc,x)=>acc.concat(f(x)),[])
}
常量转换=({comment=”“,represents=[]})=>
[注释,…回复.flatMap(转换)]
console.log(obj.map(转换))
// [
//   [
//“首次更新评论”,
//“这是对注释ID 1的回复”,
//“回复ID 5的回复”
//   ],
//   [
//“第二条评论”
//   ],
//   [
//“第三条评论”
//   ],
//   [
//“第四条评论”,
//“回复评论ID 4”
//   ],
//   [
//“测试黑色”
//   ],
//   [
//“TriHard 7注释id 7”
//   ]

//]
您可能会收到反对票,因为您没有演示自己解决问题的尝试
let obj = [
    {
        "id": 1, "comment": "First Updated Comment", "parentID": null, "replies": [{
            "id": 5, "comment": "This is a reply to comment ID 1", "parentID": 1, "replies":
                [{ "id": 9, "comment": "reply To reply ID 5", "parentID": 5, "replies": [] }]
        }]
    },
    { "id": 2, "comment": "Second Comment", "parentID": null, "replies": [] },
    { "id": 3, "comment": "Third Comment", "parentID": null, "replies": [] },
    { "id": 4, "comment": "4th Comment", "parentID": null, "replies": [{ "id": 6, "comment": "Reply to Comment ID 4 ", "parentID": 4, "replies": [] }] },
    { "id": 7, "comment": "Testing BLACK ", "parentID": null, "replies": [] },
    { "id": 8, "comment": "TriHard 7 comment id 7", "parentID": null, "replies": [] }
];
const transform = ({ comment = "", replies = [] }) =>
  [ comment, ...replies.flatMap (transform) ]

console.log (obj.map (transform))
// [
//   [
//     "First Updated Comment",
//     "This is a reply to comment ID 1",
//     "reply To reply ID 5"
//   ],
//   [
//     "Second Comment"
//   ],
//   [
//     "Third Comment"
//   ],
//   [
//     "4th Comment",
//     "Reply to Comment ID 4 "
//   ],
//   [
//     "Testing BLACK "
//   ],
//   [
//     "TriHard 7 comment id 7"
//   ]
// ]
Array.prototype.flatMap = function (f)
{
  return this.reduce ((acc, x) => acc.concat (f (x)), [])
}