最近建了一个商城,商城有个分类,后端是node,前端是vue,数据库是mysql,然后想用nodejs输出无限分类。一开始想着嵌套递归查询,发现会出现顺序问题。async和await也想过,但是感觉不太靠谱。我要分类,然后我要能够扩展。查询数据库后,转换格式。vararr=[{"id":1,"name":"手机数码","pid":0},{"id":2,"name":"家用电器","pid":0},{"id":3,"name":"美容和护肤","pid":0},{"id":4,"name":"手表和珠宝","pid":0},{"id":16,"name":"小米","pid":1},{"id":17,"name":"华为","pid":1}]完整代码:router.get('/list',function(req,res){letsql='selectid,pid,name,imgfromtable_category'vararr=[]pool.query(sql,(err,result)=>{result.forEach((item,index)=>{arr[index]={id:item['id'],name:item['name'],pid:item['pid'],img:config.static_img_url+item['img']}})res.send(tree(arr))functiontree(data){varmap={};data.forEach(function(item){map[item.id]=item;//ID这里是根据数据库字段});//console.log(map)varval=[];data.forEach(function(item){varparent=map[item.pid];//这里是parentID---pidif(parent){(parent.children||(parent.children=[])).push(item);}else{val.push(item);}});返回值;}})})输出JSON[{"id":1,"name":"手机号","pid":0,"children":[{"id":19,"name":"iPhone","pid":1},{"id":18,"name":"荣耀","pid":1},{"id":20,"name":"vivo","pid":1}]}
