ts将线性数据转为树形

177 阅读1分钟

function listTree(list) { const map: any = {}; list.forEach(item => { item.label = item.name; if (!map[item.menuId]) { map[item.menuId] = item; } });

list.forEach(item => {
  if (item.parentMenuId != 0) {
    if (map[item.parentMenuId]?.children) {
      map[item.parentMenuId]?.children.push(item)
    } else {
      if (map[item.parentMenuId]) {
        map[item.parentMenuId].children = [item];
      }
    }
  }
});

return list.filter(item => {
  if (item.parentMenuId == 0) {
    return item;
  }
})

}