Skip to content

Instantly share code, notes, and snippets.

@perymimon
Last active March 15, 2019 12:54
Show Gist options
  • Save perymimon/2f2bdfcdeb61088b4ef2131fd5397253 to your computer and use it in GitHub Desktop.
Save perymimon/2f2bdfcdeb61088b4ef2131fd5397253 to your computer and use it in GitHub Desktop.
tiny code to convert array of objects to headers and rows. For easy print to console. or create to html table
var data = [{a:1, b:2},{c:3,b:2},{d:4,a:1}];
objectsToTableRows(data);
/* return ...
{
headers:(4) ["a", "b", "c", "d"],
rows:Array(3)
0:(2) [1, 2]
1:(3) [undefined × 1, 2, 3]
2:(4) [1, undefined × 2, 4]
length:3
}*/
function objectsToTableRows(objects){
// all object headers to Set and back to Array;
const headers = [ ...new Set( objects.map( o => Object.keys(o) ).flat() ) ],
rows = objects.map( o => headers.map( h => o[h] ) )
return {headers,rows};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment