PSA: you should be using console.table()
As wonderful as the console pane is in Firefox and Chrome, its display functionalities tend to leave much to be desired.
One of the newest tools to help with this – having originated in Firebug and having been relatively recently ported over to Chrome’s main build – is console.table()
, which lets you print tables to the console! As simple as it sounds, I’ve found it to be an incredibly useful tool, especially when working with some visualization toys where a little structure goes a long way.
The most obvious way to use the command is to pass it a two-dimensional array:
console.table([[1,2,3], [4,5,6], [7,8,9]]);
It also takes a second, optional argument of columns, only printing those specific ones:
console.table([[1,2,3], [4,5,9], [7,8,15]], [0, 2]);
You can also pass a list of dicts, which is advantageous in that you get actual column headers 1:
console.table([{"first": "John", "last": "Doe"}, {"first": "Jane", "last": "Doe"}, {"first": "Rust", "last": "Cohle"}]);
And, with actual column headers, you can specify columns by string:
console.table([{"first": "John", "last": "Doe"}, {"first": "Jane", "last": "Doe"}, {"first": "Rust", "last": "Cohle"}], ["last"]);
Perhaps even more pragmatically, you can pass arbitrary objects to console.table()
and it’ll do a good job of representing them. Take this only slightly contrived instance, for example:
function Car(make, model, year) {
return {"make": make, "model": model, "year": year};
}
garage = {};
garage.primary = new Car("Honda", "Accord", 2002);
garage.secondary = new Car("Toyota", "Prius", 2011);
garage.midlife_crisis = new Car("Ford", "Thunderbird", 1964);
console.table(garage);
Compare that to the default tree view, as provided by console.log()
2:
And, just like before, you can filter by column:
console.table(garage, ["make", "model"]);