2

最近做一个商城,商城有个分类,后端是node,前端vue,数据库mysql,然后想用nodejs输出无限级分类。一开始想的是嵌套递归查询,发现会有一个先后顺序的问题,也想过async和await,感觉也不靠谱。

clipboard.png

想做分类,然后又想可以扩展。
数据库查询出来后,把格式转换了一下。

var arr = [
    {"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) {
    let sql = 'select id,pid,name,img from table_category'
    var arr = []
    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))

        function tree(data) {
            var map = {};
            data.forEach(function (item) {
                map[item.id] = item;       //这里的ID根据数据库的字段
            });
            //console.log(map)
            var val = [];
            data.forEach(function (item) {
                var parent = map[item.pid];      //这里是父级ID---pid
                if (parent) {
                    (parent.children || (parent.children = [])).push(item);
                } else {
                    val.push(item);
                }
            });
            return val;
        }
    })

})

输出JSON

[{"id":1,"name":"手机数码","pid":0,"children":[{"id":19,"name":"iPhone","pid":1},{"id":18,"name":"荣耀","pid":1},{"id":20,"name":"vivo","pid":1}]}

soso辉
84 声望2 粉丝