How to iterate through every object.child in a deeply nested object?

穿精又带淫゛_ 提交于 2021-01-29 09:32:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!