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.

2
  • Possible duplicate of How can I pretty-print JSON using JavaScript? Commented Sep 5, 2019 at 11:27
  • ^ The author doesn't want array brackets to be visible, so it is different. Commented Sep 5, 2019 at 11:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

+1 to this. Also note stringify's third parameter allows to specify whitespace for pretty-printing developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
^ The author doesn't want array brackets to be visible, so it is different.
are you sure? because I see brackets, just not on the same line
In author's example there are no commas, no double quotes and no external array [] brackets in the output.
ahh okay i see mb
|
0

You can try this one. SO Reference

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.