Get iterator for JavaScript for...in functionality

171 views Asked by At

I want to use the for...in functionality through the use of an iterator rather than calling for...in. From what I understand, I should be able to call something that JavaScript is internally calling in a for...in in order to extract the iterator. I just don't know what I need to be calling.

Basically, if I want to iterate over every key-value pair, I could do something like:

var data = {
    foo: 42,
    bar: {
        asdf: "hello world",
        qwerty: 0
    },
    baz: [3,1,4]
};

function walk(obj) {
    var stack = new Array();
    stack.push([obj.iterator, obj]);
    while (stack.length > 0) {
        if (stack[stack.length-1][0].hasNext()) {
            var next = stack[stack.length-1].next();
            document.getElementById("test").innerHTML += next + ": " + stack[stack.length-1][0][next] + "<br/>";
            stack.push(stack[stack.length-1][0][next]);
        } else {
            stack.pop();
        }
    }
}

walk(data);
Obviously, the "obj.iterator", ".next()", and ".hasNext()" are just the pseudocode, so it doesn't actually work, but that is basically what I want from the iterator.

How can I do this?

0

There are 0 answers