Search code examples
javascriptobject

Recursively looping through an object to build a property list


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

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

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


Solution

  • 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, '')
    

    Update: 17/01/2019

    There used to be a different implementation, but it didn't work. See this answer for a prettier solution