我有一張這樣的桌子:id title parent_id1 a 02 b 03 c 14 d 25 e 16 f 37 g 3我需要制作一個 json 發送到前端。我不知道如何從我的表中制作這個 json。這是關于我的目標和代碼的其他一些信息:節點類型:type Node struct { Id int64 `json:"id"' Title string `json:"title"` ParentId int64 `json:"parent_id"` Children []Node `json:"children"`}我正在使用 sqlx 從數據庫讀取到切片我需要這樣的 json:[ { "id" : 1, "title" : "a", "parent_id" : 0, "children" : [ { "id" : 3, "title" : "c", "parent_id" : 1, "children" ..... } ] }, . . .]已經有一個類似于我的問題的問題,但不同之處在于我是從 mysql 表而不是控制臺讀取節點,而且我需要將樹編組為 json
1 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
var items = select * from tbl order by parent_id;
Node.addChild = n=>this.children.add(n);
var root= new Node({Id:0, Parent:null, Title:'Root',Children:[]);
add(root, items, 0,0)
function add(tree,items, depth){
if(depth>100){
throw 'something';
}
var itemsOnThisLevel = items.where(item.parent_id==tree.id)
foreach(var item in itemsOnThisLevel){
var n = new Node(item);
tree.add(n);
add(n, items, depth+1);
}
}
- 1 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消