I have an object with children objects, and even great grandchildren objects.
I am currently using
JavaScript
x
4
1
for (const [key, value] of Object.entries(myObj)) {
2
console.log(`${key}: ${value}`);
3
}
4
Which produces, for example:
- created_at: 2021-01-01T00:00:00.000Z
- id: string
- data: [object Object]
- items: [object Object],[object Object]
How do I iterate through any number of child objects to return something similar to
- created_at: 2021-01-01T00:00:00.000Z
- id: string
- data: [object Object]
- data: 1 of 1 {contents}
- items: 1 of 2 {contents}
- items: 2 of 2 {contents}
The “1 of 2” isn’t needed, but demonstrates my output goal.
Advertisement
Answer
This is a situation where recursion is useful. For example:
JavaScript
1
11
11
1
function visitDescendants(obj, callback) {
2
for (const [key, value] of Object.entries(obj)) {
3
if (value && typeof value === "object") {
4
// Recurse
5
visitDescendants(value, callback);
6
} else {
7
callback(key, value);
8
}
9
}
10
}
11
Live example:
JavaScript
1
25
25
1
function visitDescendants(obj, callback) {
2
for (const [key, value] of Object.entries(obj)) {
3
if (value && typeof value === "object") {
4
// Recurse
5
visitDescendants(value, callback);
6
} else {
7
callback(key, value);
8
}
9
}
10
}
11
12
const obj = {
13
a: 1,
14
message: "hi",
15
b: {
16
nestedMessage: "there",
17
c: {
18
furtherNestedMessage: "folks!"
19
},
20
},
21
};
22
23
visitDescendants(obj, (key, value) => {
24
console.log(`${key}: ${value}`);
25
});