How To Iterate Through Every Object.child In A Deeply Nested Object?
I have following structure: instance: { children: [instance, instance ...] } As you can see each instance has children array with another instances in it, hence this repetition
Solution 1:
You can recursively iterate over all instances:
function iterate(instance) {
for (let child of instance.children) {
iterate(child);
}
}
Example:
instance = {
name: 'Parent',
children: [{
name: 'Child 1',
children: []
}, {
name: 'Child 2',
children: [{
name: 'Grandchild 1',
children: []
}]
}]
};
functioniterate(instance, f) {
if (f)
f(instance.name);
for (let child of instance.children) {
iterate(child, f);
}
}
iterate(instance, console.log);
Output:
Parent
Child 1
Child 2
Grandchild 1
Post a Comment for "How To Iterate Through Every Object.child In A Deeply Nested Object?"