求助:根据条件将评论/回复对象转换为对象的数组的数组
把扁平评论转成嵌套数组结构的解决方案
嘿,同学!我来帮你搞定这个评论嵌套的问题~ 把扁平的评论列表转成嵌套的数组结构其实没那么难,咱们一步步来:
核心思路
- 先建立一个评论ID到评论对象的映射,这样能快速定位任意评论的父评论,避免重复遍历数组浪费时间
- 遍历每一条评论,把它挂载到对应父评论的子列表中(如果父评论存在的话)
- 最后收集所有没有父评论(或父ID对应的评论不存在)的顶级评论,这些就是最外层数组的元素
代码实现(以JavaScript为例)
先补全你提供的截断数据,然后写实现代码:
// 你的原始扁平评论数组(补全了截断部分) const flatComments = [ {"id":9,"comment":"This is a normal comment to the post SON","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null}, {"id":22,"comment":"new made comment","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null}, // 新增一条回复示例,用来展示多层嵌套效果 {"id":25,"comment":"Reply to the first comment!","commentername":"anotherUser","parentID":9,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null} ]; // 方法1:带children属性的嵌套对象数组(前端渲染评论区最常用的结构) function nestCommentsWithChildren(flatComments) { // 1. 创建评论映射,同时给每个评论添加children空数组 const commentMap = {}; flatComments.forEach(comment => { commentMap[comment.id] = {...comment, children: []}; }); // 2. 挂载子评论并收集顶级评论 const nestedComments = []; Object.values(commentMap).forEach(comment => { const parentComment = commentMap[comment.parentID]; if (parentComment) { // 如果父评论存在,将当前评论加入父评论的children数组 parentComment.children.push(comment); } else { // 否则就是顶级评论,加入结果数组 nestedComments.push(comment); } }); return nestedComments; } // 方法2:严格的数组嵌套格式(数组的数组) function nestAsArrayOfArrays(flatComments) { // 每个评论在映射中存储为 [评论对象, 子评论数组] const commentMap = {}; flatComments.forEach(comment => { commentMap[comment.id] = [comment, []]; }); const nestedResult = []; Object.values(commentMap).forEach(([comment, childrenArr]) => { const parentEntry = commentMap[comment.parentID]; if (parentEntry) { // 将当前评论的数组项加入父评论的子数组 parentEntry[1].push([comment, childrenArr]); } else { // 顶级评论直接加入结果数组 nestedResult.push([comment, childrenArr]); } }); return nestedResult; } // 调用方法获取结果 const nestedWithChildren = nestCommentsWithChildren(flatComments); const nestedArrayOfArrays = nestAsArrayOfArrays(flatComments); console.log("带children的嵌套结构:", nestedWithChildren); console.log("纯数组嵌套结构:", nestedArrayOfArrays);
结果说明
- 方法1的结果是每个评论对象自带
children数组,存储它的所有回复,这是前端渲染评论区最常用的结构 - 方法2的结果是严格的数组的数组格式,比如顶级元素是
[评论对象, [子评论数组]],完全符合你想要的嵌套数组要求
如果你的评论数据里有更多层级的回复(比如回复的回复),这两个方法都能自动处理多层嵌套哦~
内容的提问来源于stack exchange,提问作者Jessica Goldberg
相关产品推荐
相关产品推荐

