#Custom console.log formatting for a class/object

7 messages · Page 1 of 1 (latest)

knotty shale
#

Is there a way to change the way an object/class is printed in the console?

For example, instead of

[1, 2, 3, 4]
```, I want the particular object to be printed as

[1, 2
3, 4]

dusky torrent
#

Here's a little example it showing off

const myarray = [1, 2, 3, 4, 5, 6];

console.log(myarray);
console.log(Deno.inspect(myarray, {
  breakLength: 28,
}));
Object.defineProperty(myarray, Symbol.for("Deno.customInspect"), {
  value() {
    const splits = String(this).split(",");
    let str = "";
    for (let i = 0; i < splits.length; i += 2) {
      str += (i !== 0 ? " " : "") + (splits[i] + ", " + splits[i + 1] ?? "") +
        (i > splits.length / 2 ? "" : "\n");
    }
    return `[${str}]`;
  },
});
console.log(myarray);

stdout

[ 1, 2, 3, 4, 5, 6 ]
[
  1,
  2,
  3,
  4,
  5,
  6
]
[1, 2
 3, 4
 5, 6]
#

you can also define it for specific object classes as well if you want, or implement the symbol in your own class

Object.defineProperty(Array.prototype, Symbol.for("Deno.customInspect"), { ... })
knotty shale
#

Ooh thank you