根据每项的parentId
,生成具体树形结构的对象。
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); // [{ id: 1, parent_id: null, children: [...] }]
原文地址:https://www.cnblogs.com/zhenguo-chen/p/12032230.html
时间: 2024-11-12 10:55:41