我有 2 個代表樹結構的類,如下所示:
class Node {
private _id: string;
name: string;
parent?: Node;
children: Node[];
}
class Tree {
root: Node;
treeMap: Map<string, Node>;
}
我正在撰寫一個GET /tree應該以下列方式回傳樹 json 的 api:
[
{
"1": {
"name": "root",
"children": [
{
"2": {
"name": "fish",
"children": [] // empty children
}
},
{
"3": {
"name": "bird",
"children": [ ...<any children>... ]
}
}
]
}
}
]
當我這樣做時ctx.body = tree,api回傳:
{
"root": {
"_id": "1",
"name": "root",
"children": [
{
"_id": "2",
"name": "fish",
"children": []
},
{
"_id": "3",
"name": "bird",
"children": []
}
]
},
"treeNodeMap": {}
}
將其轉換為所需的 json 格式的正確方法是什么?
uj5u.com熱心網友回復:
讓您的類實作toJSON()以生成您想要的資料結構。
// Define the data structure
interface SerialisedNode {
[id: string]: {
name: string;
children: SerialisedNode[]
}
}
class Node {
private _id: string;
name: string;
parent?: Node;
children: Node[];
toJSON(): SerialisedNode {
return {
[ this._id ]: {
name: this.name,
children: this.children.map(node => node.toJSON())
}
}
}
}
class Tree {
root: Node;
treeMap: Map<string, Node>;
toJSON(): SerialisedNode {
return this.root.toJSON();
}
}
當您的Tree(或任何Node)被字串化為 JSON 時,轉換將啟動并提供備用資料結構。
TypeScript Playground 演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445685.html
標籤:javascript json 打字稿
上一篇:重構Javascript物件遍歷
