问题
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 can go relatively deep until last nested child is reached. I need to iterate through each child of uppermost / given instance
and perform a simple if
condition. But I can't figure out how to do that as length of children
can vary, plus we need to check children of each child and so on...
回答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: []
}]
}]
};
function iterate(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
来源:https://stackoverflow.com/questions/64750206/how-to-iterate-through-every-object-child-in-a-deeply-nested-object