jQuery-如何递归循环对象的嵌套属性? [英] jQuery - How to recursively loop over an object's nested properties?

查看:373
本文介绍了jQuery-如何递归循环对象的嵌套属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以递归地遍历JS/jQuery对象的所有嵌套属性?

Is there are a way to recursively loop over all the nested properties of a JS/jQuery object?

例如,给定此对象

var x = {
    'name': 'a',
    'level': 1,
    'children': [{
        'name': 'b',
        'level': 2,
        'children': [{
            'name': 'c',
            'level': 3,
            'children': [{
            ...
            }]
        }]},
        ...
    }]
}

我如何无限循环遍历名为"a"和其子代,"b"和其子代,"c"和其子代的对象?

how could I loop over the objects named 'a' and their children, 'b' and their children, 'c' and their children, ad infinitum?

推荐答案

递归方法似乎是最好的,就像这样:

A recursive approach seems best, something like this:

function recursiveIteration(object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            if (typeof object[property] == "object"){
                recursiveIteration(object[property]);
            }else{
                //found a property which is not an object, check for your conditions here
            }
        }
    }
}

这是一个有效的小提琴

这篇关于jQuery-如何递归循环对象的嵌套属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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