1

I recently found out you can add colors and basic CSS to console.log() calls with the use of the %c character. (Learned about it from this answer Colors in JavaScript console)

It works well for string values. However, I tried logging an array, and got a pretty disappointing result. It logged it as [object Object], instead of giving me an interactive view of the array, and the ability to expand it, so I could look at the objects inside.

I am aware you can use JSON.stringify to see ALL the content, but I want the default functionality of console.log so I can fold and expand at will, to avoid clutter in the console.

Is there a solution for this?

Code I have used:

console.log(`%csuccess`, 'background-color: #2FA745; color: #fff; display: block; padding: 4px;');
const myArray = [{test: 'hi'},{test2: 'hello'}];
console.log(`%c${myArray}`, 'background-color: #2FA745; color: #fff; display: block; padding: 4px;');
console.log('default behaviour of array', myArray);

enter image description here

Daniel B.
  • 2,491
  • 2
  • 12
  • 23
  • Not that I know, but you can use `%c${JSON.stringify(myArray)}` so you'll at least see the contents. –  Jun 30 '20 at 08:16
  • @ChrisG I am aware of JSON.stringify, however i want the default functionality so i can expand and fold at will, so it wont clutter up the console. – Daniel B. Jun 30 '20 at 08:19
  • @DanielB. There is no other functionality to color the console with just doing this `%c${myArray}` You have to use `JSON.stringify` if not then i would rec-emend dont use color. – Always Helping Jun 30 '20 at 08:22
  • Another option for (multidimensional) arrays and objects (or objects inside arrays) is the `console.table()` function. Doesn't give you CSS styling but it really helps with the readability – Reyno Jun 30 '20 at 08:23
  • The only other thing I can think of is console.logging a bunch of colored dashes before and after the array. –  Jun 30 '20 at 08:23

2 Answers2

0

Kind of. You can use JSON.stringify, but I'm sure that's not what you're looking for. You can't style them with the usual functionality (drop downs, prototype, etc...) because they need to be strings to be styled. I hope this helps!

NintendoZaedus
  • 653
  • 3
  • 8
  • 22
0

Per the specification for console.log you should use %o and other substitutions:

console.log(`%c%o / %c%d %c[%s]`,
  'color: red', [{test: 'hi'},{test2: 'hello'}],
  'color: green', 123,
  'color: cyan', 'foo');
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • I tried running this code. The first styling (color red) is being applied to the '/' character and not to the array. – Daniel B. Jun 30 '20 at 09:02
  • Of course, for that you'll have to use [Custom Formatters](https://www.google.com/search?q=devtools+Custom+Formatters). – wOxxOm Jun 30 '20 at 09:05