扁平数据根据`parentId`生成树结构
时间:2019-12-12 23:50:14
收藏:0
阅读:375
根据每项的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
评论(0)