递归循环遍历对象以构建属性列表 [英] Recursively looping through an object to build a property list

查看:140
本文介绍了递归循环遍历对象以构建属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我有一个包含多个子和子子对象的大对象,其属性包含多种数据类型。出于我们的目的,此对象如下所示:

Situation: I have a large object containing multiple sub and sub-sub objects, with properties containing multiple datatypes. For our purposes, this object looks something like this:

var object = {
    aProperty: {
        aSetting1: 1,
        aSetting2: 2,
        aSetting3: 3,
        aSetting4: 4,
        aSetting5: 5
    },
    bProperty: {
        bSetting1: {
            bPropertySubSetting : true
        },
        bSetting2: "bString"
    },
    cProperty: {
        cSetting: "cString"
    }
}

我需要遍历此对象并构建一个列表显示层次结构的键,因此列表最终看起来像这样:

I need to loop through this object and build a list of the keys that shows the hierarchy, so the list ends up looking like this:

aProperty.aSetting1
aProperty.aSetting2
aProperty.aSetting3
aProperty.aSetting4
aProperty.aSetting5
bProperty.bSetting1.bPropertySubSetting
bProperty.bSetting2
cProperty.cSetting

我有这个功能,它会循环通过对象和spi键出来但不是分层次的:

I've got this function, which does loop through the object and spit out the keys, but not hierarchically:

function iterate(obj) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (typeof obj[property] == "object") {
                iterate(obj[property]);
            }
            else {
                console.log(property + "   " + obj[property]);
            }
        }
    }
}

可以有人让我知道怎么做?这里有一个混乱的方法: http://jsfiddle.net/tbynA/

Can somebody let me know how to do this? Here's a jsfiddle for you to mess with: http://jsfiddle.net/tbynA/

推荐答案

我做了一个 FIDDLE 。我存储一个堆栈字符串然后输出它,如果该属性是基本类型:

I made a FIDDLE for you. I am storing a stack string and then output it, if the property is of primitive type:

function iterate(obj, stack) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    console.log(property + "   " + obj[property]);
                    $('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
    }

iterate(object, '')

这篇关于递归循环遍历对象以构建属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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