nodejs無限級分類

最近作一個商城,商城有個分類,後端是node,前端vue,數據庫mysql,而後想用nodejs輸出無限級分類。一開始想的是嵌套遞歸查詢,發現會有一個前後順序的問題,也想過async和await,感受也不靠譜。前端

clipboard.png

想作分類,而後又想能夠擴展。
數據庫查詢出來後,把格式轉換了一下。vue

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}
]

完整代碼:node

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;
        }
    })

})

輸出JSONmysql

[{"id":1,"name":"手機數碼","pid":0,"children":[{"id":19,"name":"iPhone","pid":1},{"id":18,"name":"榮耀","pid":1},{"id":20,"name":"vivo","pid":1}]}
相關文章
相關標籤/搜索