Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
Typescript classes deserialized json

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

TypeScript Playground Demo

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda