Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

How to implicitly log a JavaScript object as a string?

Consider:

var o = { a: 1, b: 2, toString: function() { return "foo"; } };

In Chrome dev tools:

Debug Screenshot

Is there anything I could do to the object such that o is displayed in the debug console as "foo" instead of the full object?

Upvotes: 3

Views: 220

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70139

Here's my attempt:

(function() {
    var cl = console.log;
    console.log = function() {
        cl.apply(console, [].slice.call(arguments).map(function(el) {
            return {}.toString.call(el) === '[object Object]' && typeof el.toString === 'function' && el.toString !== Object.prototype.toString ? el.toString() : el;
        }));
    };
}());

^ Just throw this script before any console.log call.


Test case:

console.log('str', 42, /rege?x/, { a: 1 }, [1, 2], {
        toString: function() { return "foo"; }
    }, new function() {
        this.toString = function() {
            return 'bar';
        };
    }
);

console.log output


This just maps plain/constructed objects which have a toString method different from Object.prototype.toString to their .toString() value. I chose this way over hasOwnProperty as constructors may also have a toString method in their prototype.

As you can see, all objects and even primitives inherit a toString method from the native constructors, so you may need tweaking for specific use cases. The snippet above does not stringify function objects with custom toString properties, for example.

Upvotes: 2

Related Questions