Search code examples
javascriptjqueryrecursiontype-conversionobject-to-string

"too much recursion" in this recursive function written in JavaScript (obj2str)


What's wront with this piece of code:

function obj2string(obj) {
    var result = '';

    for(var i in obj) {
        if(typeof(obj[i]) === 'object') {
            result += obj2string(obj[i]);
        } else {
            result += i + " => " + obj[i] + "\n";
        }
    }

    return result;
}

It's supposed to recursively concentate the result string with new properties, however there's at somepoint too much recursion.

I was passing an object like this: $(this); -> from jQuery.

$(this)

Being an instance of this jQuery selector: $('.debug'); witch has one class matched in the current document.


Solution

  • if(typeof(obj[i]) === 'object') { will execute if obj[i] is null. Are you aware of that? Try it with $.isPlainObject() (source)