利用nodejs读取数据库数据生成树结构的json数据

mac2022-06-30  16

在做后台管理界面的时候,几乎少不了的一个结构就是树形结构,用来做菜单导航;

那么,最希望的就是树结构的所有数据都是读取的数据库,而不是直接代码当中写死,那我们就一步一步来看:

一,建表

字段通常包括:id,text,url,pid

idtexturlpid1a 02btest.html1

二,使用nodeJS连接数据库

const mysql = require('mysql'); //注入MySQL模块 const connection = mysql.createConnection({ //连接数据库的信息 host:'', //数据库的地址,如:localhost user:'', //登录名 默认root   password:'',  //登录密码 database:''    //数据库名字 });connection.connect(); //创建连接

三,读取数据

connection.query('SELECT*FROM 表名',function(err,rows){}); //rows为读过来的数据

 

四,把读过来的数据转成树结构的json数据   //举例读取的数据为list的数据var list = [{"id":1,"user":"a","pid":0},{"id":2,"user":"b","pid":1},{"id":3,"user":"c","pid":0},{"id":4,"user":"d","pid":3}]; var rJson = [];//将所有的pid的数据加到对应的id数据对象里面去,需要添加一个属性children for(var i=0;i<list.length;i++){ var arr = []; for(var j=0;j<list.length;j++){ if(list[i].id == list[j].pid){ list[i].children = arr; arr.push(list[j]); } } } for(var i=0;i<list.length;i++){ if(list[i].pid == 0){ rJson.push(list[i]); } } console.info(rJson);

 

自己是这么做的,有问题或者不足的地方,希望各位大牛指正!

转载于:https://www.cnblogs.com/Immortal-brother/p/8336572.html

相关资源:NodeJs实现读取目录文件,以及文件批量生成
最新回复(0)