Skip to content

Instantly share code, notes, and snippets.

@darthmall
Last active April 21, 2018 14:46
Show Gist options
  • Save darthmall/58efa6d88e56712730548c02ad154e2d to your computer and use it in GitHub Desktop.
Save darthmall/58efa6d88e56712730548c02ad154e2d to your computer and use it in GitHub Desktop.
Convert data formatted as a tabular array into an array of objects for easier use with D3
var table = [
[“STATE”, “DATE”, “ANOTHERTHING”], // Header row
[“ALABAMA”, “2000”, “MORESTUFF”],
[“ALASKA”, “2000”, “OTHERSTUFF”]
];
var data = tableToArray(table[0], table.slice(1));
data[0] // {"STATE": "ALABAMA", "DATE": "2000", "ANOTHERTHING": "MORESTUFF"}
/**
* Convert a tabular Array into an Array of Objects.
*
* @param {string[]} headers - A name for each column in the table
* @param {Array[]} rows - An array of rows from the table, each row
* is an array of column values
*
* @return {Object[]} An Array of Objects, each object has a property
* for each of the headers in the table
*/
function tableToArray(headers, rows) {
var n = headers.length;
// Convert each row, which is an Array of values, into an object
// whose property names are the headers and whose values are the
// corresponding values of the array.
return rows.map(function (row) {
var obj = {};
// Add each column defined by `headers` from this row onto
// the object that we return.
for (var i = 0; i < n; i++) {
obj[headers[i]] = row[i]
}
return obj;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment