我正在使用Nodejs,Express,MySQL,EJS。
用户可以创建帖子,评论/回复评论/回复这些帖子的回复。
问题:我不知道如何以允许我在EJS中呈现它们的方式将数据排序到对象/数组中。我知道如何评论和回复评论,但不回复回复。如何创建一个对象/数组(或对象/数组),使其更容易/更简单"管理回复(......等)回复的评论,回复和回复?
这个想法:我认为最终产品应该是这样的:
"评论" MySQL表是:
ID comment ReplyToCommentID
--------------------------------------------------------
1 | First Updated Comment | NULL
2 | Second Comment | NULL
3 | Third Comment | NULL
4 | 4th Comment | NULL
5 | This is a reply to comment ID 1 | 1
6 | Reply to Comment ID 4 | 4
7 | Testing here | NULL
8 | TriHard 7 comment id 7 | NULL
ReplyToCommentID中的值表示注释是对具有该值的ID的注释的回复,ID为5和6的注释是对ID为1和4的注释的回复,如果它为NULL,则为意味着它是对帖子的正常评论。
从MySQL到Node将它们以这种格式返回:
[{"id":1,"comment":"First Updated Comment","ReplyToCommentID":null},{"id":2,"comment":"Second Comment","ReplyToCommentID":null},{"id":3,"comment":"Third Comment","ReplyToCommentID":null},{"id":4,"comment":"4th Comment","ReplyToCommentID":null},{"id":5,"comment":"This is a reply to comment ID 1","ReplyToCommentID":1},{"id":6,"comment":"Reply to Comment ID 4","ReplyToCommentID":4},{"id":7,"comment":"Testing here","ReplyToCommentID":null},{"id":8,"comment":"TriHard 7 comment id 7","ReplyToCommentID":null}]
将评论和回复分成他们自己的对象给出了这一点。 (显然)
this is replies {"1":"This is a reply to comment ID 1","4":"Reply to Comment ID 4"}
This is comments {"1":"First Updated Comment","2":"Second Comment","3":"Third Comment","4":"4th Comment","7":"Testing here","8":"TriHard 7 comment id 7"}
我花了几天时间试图解决这个问题,但对于我的学生体验来说,这似乎太过分了。#34; (我是自学成才,因此我没有人在现实生活中寻求帮助)
如果你帮助我,我将非常感激。
感谢您的时间。
答案 0 :(得分:0)
您目前有一个清单。但你实际上想要一个&#34树视图"。因此,将列表转换为树是有意义的。此时我们还可以整理根节点:
const roots = [];
const byId = new Map();
for(const reply of replies)
byId.set(reply.id, reply);
for(const reply of replies) {
const {ReplyToComment} = reply;
if(ReplyToComment) {
const parent = byId.get(ReplyToComment);
(parent.children || (parent.children = [])).push(reply);
} else {
roots.push(reply);
}
}
现在roots
看起来像这样:
[{
id: 1,
/*...*/
children: [{
id:2,
ReplyToComment:1
}, /*...*/]
}, /*...*/ ]
如何将它渲染到您的页面是您的事情,但是递归方法看起来像:
function show(replies, depth = 0) {
for(const reply of replies) {
console.log(" ".repeat(depth) + reply.comment);
show(reply.children || [], depth + 1);
}
}
show(roots);
现在控制台输出将是
comment
reply
reply
reply
...
html可以采用类似的东西。