Consider:
var o = { a: 1, b: 2, toString: function() { return "foo"; } };
In Chrome dev tools:

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?
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.
console.log('str', 42, /rege?x/, { a: 1 }, [1, 2], {
toString: function() { return "foo"; }
}, new function() {
this.toString = function() {
return 'bar';
};
}
);

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With