parent_id =null 是一级数据
parent_id = comment_id 是comment_id的子数据
根据'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)