Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda