I have 2 classes that represent a Tree structure as follows:
class Node {
private _id: string;
name: string;
parent?: Node;
children: Node[];
}
class Tree {
root: Node;
treeMap: Map<string, Node>;
}
I am writing a api GET /tree
which should return tree json in the following manner:
[
{
"1": {
"name": "root",
"children": [
{
"2": {
"name": "fish",
"children": [] // empty children
}
},
{
"3": {
"name": "bird",
"children": [ ...<any children>... ]
}
}
]
}
}
]
when I do ctx.body = tree
this is what the api returns:
{
"root": {
"_id": "1",
"name": "root",
"children": [
{
"_id": "2",
"name": "fish",
"children": []
},
{
"_id": "3",
"name": "bird",
"children": []
}
]
},
"treeNodeMap": {}
}
What would be the right way to convert it to the desired json format?
CodePudding user response:
Have your classes implement toJSON() to produce the data structure you want.
// 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();
}
}
When your Tree
(or any Node
) is stringified as JSON, the transform will kick in and deliver the alternate data structure.