Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Matt Johnson-Pint Avatar asked Mar 02 '26 22:03

Matt Johnson-Pint


1 Answers

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.

like image 62
Fabrício Matté Avatar answered Mar 05 '26 12:03

Fabrício Matté