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!
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))