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

181
Vistas
Print object properties using recursion

I need help with writing a javascript function that gets a class as a parameter, and prints all its public properties (name and value) using reflection with indentation.

Some properties can be of type class so the properties need to be printed with the correct indentation.

Example:

Class A {
  a1;
  a2;

  constructor() {
    this.a1 = 'a';
    this.a2 = 2;
  }
}


Class B {
  b1;
  b2;

  constructor() {
    this.b1 = true;
    this.b2 = new A();
  }
}

When getting class B as a parameter the output should be:

Object:
----------------------------------------
  b1 = true,
  b2 = 
  Object:
  ----------------------------------------
    a1 = "a",
    a2 = 2
  
{

Thank you!

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

0

You could use a recursive function that return formatted string recursively,

class A { a1 = 'a'; a2 = 2; }
class B { b1 = true; b2 = new A; }

function format(object, indent_lvl = 1) {
    let str = "Object:\n" + "\t".repeat(indent_lvl - 1) + "----------------------------------------";
    let indent = "\n" + "\t".repeat(indent_lvl);
    for (let [key, value] of Object.entries(object)) {
        if (typeof value == "object")
            value = indent + format(value, indent_lvl + 1);

        str += indent + key + " = " + value;
    }
    return str;
}

console.log(format(new B))

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