0

How would I get the following object:

[ 'hello everyone!', { testing: 1 }, 'another:', { state: 1 } ]

To print as the following:

hello everyone! { 
    testing: 1 
} another: { 
    state: 1 
}

The objects in the array can be heavily nested.

I use this right now, but feels like it's heavy:

const messages = [ 'hello everyone!', { testing: 1 }, 'another:', { state: 1 } ];
let string = '';
messages.forEach(element => {
    string += ' ';
    if (typeof element === 'string') {
        string += element;
    } else {
        string += util.inspect(element, { showHidden: false, depth: null, compact: false });
    }
});
console.log(string);

Bonus for elegant code.

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • Possible duplicate of [How can I pretty-print JSON using JavaScript?](https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) – VLAZ Sep 05 '19 at 11:27
  • ^ The author doesn't want array brackets to be visible, so it is different. – dziraf Sep 05 '19 at 11:32

2 Answers2

2

You could use JSON.stringify()

console.log(JSON.stringify(yourData));

This should help see the data better in the terminal. Not elegant or anything but simple at least. Admittedly doesn't give the nesting but shows the full object and should maintain to do so with deeper nesting.

enter image description here

As mentioned in the comments by Gavin this also has a pretty-printing argument to help achieve the nesting.

console.log(JSON.stringify(yourData, null, 2));

Which would give you

enter image description here

devDan
  • 5,969
  • 3
  • 21
  • 40
0

You can try this one. SO Reference

console.log(JSON.stringify([ 'hello everyone!', { testing: 1 }, 'another:', { state: 1 } ], null, 2))