Pretty Printing Deep Javascript Objects | Task

Ole Ersoy
Feb - 14  -  1 min

Scenario

We have a nested object graph composed like this:

class Task {
  constructor(public id: number, public description, public previous?: Task) {}
}

const first = new Task(1, 'First');
const last = new Task(1, 'Last', first);

And we want to pretty print it so that we can see the structure and values like this:

{
id: 1,
description: "Last",
previous: {
      id: 1,
      description: "First",
      previous: undefined
}

Approach

First install stringify-object:

npm i -D stringify-object @types/stringify-object

Print (log) the graph like this:

const s = stringifyObject(last, {
  indent: '      ',
  singleQuotes: false,
});
console.log(s);

Demo