扁平数据根据`parentId`生成树结构

根据每项的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: [...] }]

猜你喜欢

转载自www.cnblogs.com/zhenguo-chen/p/12032230.html