Learn how to use console.table to render arrays and objects in a tabular format for easy scanning over the values. We'll create some mock data and then render it to the log in various ways to explore console.table's API.
My favorite one of the console utility logging methods is the one that I actually didn't know about, until I started doing research to prepare for this course, and that is cosole.table. It works like this. Let's create a bunch of mock data first.
We're going to say function character, and it gets a name and a power. Then let's create a couple characters. Let's save VarBuffy equals new character. Her name is Buffy. Her power is that she's the slayer. VarWillow is a new character. Her name is Willow. Her power is that she's a witch. VarSpike is a new character, his name is Spike, and he's a vampire.
If we wanted to create a list of these characters, we could say VarChars equals Buffy, Willow, Spike. What if we wanted to log this out? We know that console.log takes any type of argument we want to throw at it, so we can do that, and we can see that we've got an array of three characters. We can open that up, we can open that up, and we can see there's that character, there's that character, there's that character.
That's great, but it's kind of a pain in the butt to have to step through and drill that down that deeply into what really is a pretty simple data set. Instead of using console.log, we can use console.table, and that's going to give us this beautifully rendered view that shows us every item in our array, with its index. Because it's an array, we get 0, 1, and 2, and then, with all the properties of the objects in the array.
We can take this a bit further though. Well, not with arrays, we can't. But, if we wanted to change characters, so that instead of being just an array, we wanted to make it an object. Let's do VarChars by Name. We can say Buffy is Buffy, Willow is Willow, and Spike is Spike. We can log out chars by Name, using console.table.
You can see, when you've got an object well-defined fields here, that the index, instead of being 0, 1, 2, like it is in an array, instead becomes the name for that item in that array. And, when you're logging out using console.table and object, you can specify a second argument here, which is the list of columns you'd want to show.
If I say only Power, then I get the index -- because you always get the index -- and I get the Power, and it removed the name. If I wanted to add Name here, then we go back to our original view. And, if I wanted to pass in an empty array, that's going to take out all of the fields, except for the index.