JS 用递归整合评论数据

parent_id =null 是一级数据
parent_id = comment_id 是comment_id的子数据

Snipaste_2020-10-02_23-51-43.png

根据'parent_id'生成一个树型结构

const nest = (items, id = null, link = 'parent_id') => items.filter(item => item[link] === id).map(item => ({ ...item, children: nest(items, item.id) }))
// 使用案例
const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
]
const nestedComments = nest(comments)
console.log("🚀 ~ file: 根据'parent_id'生成一个树型结构.html ~ line 22 ~ nestedComments", nestedComments)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容