如何遍历深层嵌套对象中的每个object.child? [英] How to iterate through every object.child in a deeply nested object?

查看:90
本文介绍了如何遍历深层嵌套对象中的每个object.child?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

instance: {
  children: [instance, instance ...]
}

如您所见,每个 instance 都具有 children 数组,其中包含另一个实例,因此这种重复可以进行得相对较深,直到到达最后一个嵌套的子级为止.我需要遍历最高/给定的 instance 的每个孩子,并执行一个简单的 if 条件.但是我不知道该怎么做,因为 children 的长度会有所不同,另外我们需要检查每个孩子的孩子,依此类推...

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...

推荐答案

您可以递归地迭代所有实例:

You can recursively iterate over all instances:

function iterate(instance) {
  for (let child of instance.children) {
    iterate(child);
  }
}

示例:

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);

输出:

Parent
Child 1
Child 2
Grandchild 1

这篇关于如何遍历深层嵌套对象中的每个object.child?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆