Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!