let menus = [
  { "id": "1", "parentID": "0", "name": "家用电器" },
  { "id": "4", "parentID": "1", "name": "大家电" },
  { "id": "5", "parentID": "1", "name": "生活电器" },
  { "id": "2", "parentID": "0", "name": "服饰" },
  { "id": "3", "parentID": "0", "name": "化妆" },
  { "id": "7", "parentID": "4", "name": "空调" },
  { "id": "8", "parentID": "4", "name": "冰箱" },
  { "id": "9", "parentID": "4", "name": "洗衣机" },
  { "id": "10", "parentID": "4", "name": "热水器" },
  { "id": "7", "parentID": "4", "name": "空调" },
  { "id": "11", "parentID": "3", "name": "面部护理" },
  { "id": "12", "parentID": "3", "name": "口腔护理" },
  { "id": "13", "parentID": "2", "name": "男装" },
  { "id": "14", "parentID": "2", "name": "女装" },
  { "id": "15", "parentID": "7", "name": "海尔空调" },
  { "id": "16", "parentID": "7", "name": "美的空调" },
  { "id": "19", "parentID": "5", "name": "加湿器" },
  { "id": "20", "parentID": "5", "name": "电熨斗" },
];
function buildTree (menus) {
  const map = {};
  const tree = [];
  menus.forEach(menu => {
    map[menu.id] = { ...menu, children: [] };
  });
  menus.forEach(menu => {
    const parent = map[menu.parentID];
    if (parent) {
      parent.children.push(map[menu.id]);
    } else {
      tree.push(map[menu.id]);
    }
  });
  return tree;
}
const treeMenus = buildTree(menus);

Last Updated:
Contributors: pengrengui