Recursive Iterations of Object

Recursively Iterate an Object that Contains Sub-Objects

by mmansion

JavaScript

var obj = {
    prop1: 'val1',
    prop2: 'val2',
    obj1: {
        prop1: 'obj1-val1',
        prop2: 'obj1-val2'
    },
    obj2: {
        prop1: 'obj2-val1',
        prop2: 'obj2-val2'
    }
}

//method 1

function iterate(obj) {
    for (i in obj) {
        if (typeof(obj[i]) == "object" && !isEmpty(obj[i])) {
            iterate(obj[i]); //recursion
        } else {
            document.write(obj[i]);
            document.write("<hr>");
        }
    }
}

function isEmpty(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false;
        }
    }
    return true;
}

//method 2

function iterate2(obj) { //print obj to source in remote debugger      
    var list = [];
    if (typeof obj == 'function') {
        return '<function>';
    } else if (obj instanceof Array) {
        for (var i = 0; i < obj.length; ++i) {
            list.push(iterate2(obj[i]));
        }
        return '[' + list.join(',') + ']';
    } else if (typeof obj == 'object') {
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                list.push((key).toString() + ':' + iterate2(obj[key]));
            }
        }

        return '{' + list.join(',') + '}';
    } else {
        return (obj).toString();
    }
}

var myList = iterate2(obj);

document.write(myList);