Is there a way (in jQuery or JavaScript) to loop through each object and it's children and grandchildren and so on?

如果是的话...我也能读一下他们的名字吗?

Example:

foo :{
  bar:'',
  child:{
    grand:{
      greatgrand: {
        //and so on
      }
    }
  }
}

so the loop should do something like this...

loop start
   if(nameof == 'child'){
     //do something
   }
   if(nameof == 'bar'){
     //do something
   }
   if(nameof =='grand'){
     //do something
   }
loop end

推荐答案

您正在寻找for...in循环:

for (var key in foo)
{
    if (key == "child")
        // do something...
} 

Be aware that for...in loops will iterate over any enumerable properties, including those that are added to the prototype of an object. To avoid acting on these properties, you can use the hasOwnProperty method to check to see if the property belongs only to that object:

for (var key in foo)
{
    if (!foo.hasOwnProperty(key))
        continue;       // skip this property
    if (key == "child")
        // do something...
}

Performing the loop recursively can be as simple as writing a recursive function:

// This function handles arrays and objects
function eachRecursive(obj)
{
    for (var k in obj)
    {
        if (typeof obj[k] == "object" && obj[k] !== null)
            eachRecursive(obj[k]);
        else
            // do something... 
    }
}

Jquery相关问答推荐

如何使 Bootstrap 轮播滑块使用移动左/右滑动

如何使用 jQuery 的 drop 事件上传从桌面拖动的文件?

加载外部 css 文件,如 jquery 中的脚本,这在 ie 中也兼容

为什么对同一个 ASP.NET MVC 操作的多个同时 AJAX 调用会导致浏览器阻塞?

jQuery 与 javascript?

如何使用 jQuery go 除 HTML 标签?

jQuery .get 错误响应函数?

javascript:检测滚动结束

jQuery计算所有文本字段中的值的总和

JQuery .hasClass 用于 if 语句中的多个值

jquery变量语法

使用 jQuery 将宽度设置为百分比

隐藏 div 但保留空白

如何签入用户已在 Google recaptcha 中选中复选框的 js?

判断复选框是否未选中单击 - jQuery

jQuery Uncaught TypeError: 对象 [object Window] 的属性$不是函数

jQuery、复选框和 .is(":checked")

如何将键和值都推送到 Jquery 中的数组中

粘性侧边栏:向下滚动时固定在底部,向上滚动时固定在顶部

jQuery,简单的轮询示例