I have an object with children objects, and even great grandchildren objects.
I am currently using
for (const [key, value] of Object.entries(myObj)) {
console.log(`${key}: ${value}`);
}
Which produces, for example:
How do I iterate through any number of child objects to return something similar to
The "1 of 2" isn't needed, but demonstrates my output goal.
This is a situation where recursion is useful. For example:
function visitDescendants(obj, callback) {
for (const [key, value] of Object.entries(obj)) {
if (value && typeof value === "object") {
// Recurse
visitDescendants(value, callback);
} else {
callback(key, value);
}
}
}
Live example:
function visitDescendants(obj, callback) {
for (const [key, value] of Object.entries(obj)) {
if (value && typeof value === "object") {
// Recurse
visitDescendants(value, callback);
} else {
callback(key, value);
}
}
}
const obj = {
a: 1,
message: "hi",
b: {
nestedMessage: "there",
c: {
furtherNestedMessage: "folks!"
},
},
};
visitDescendants(obj, (key, value) => {
console.log(`${key}: ${value}`);
});