Skip to content

Instantly share code, notes, and snippets.

@bgmort
Last active December 21, 2015 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgmort/6311947 to your computer and use it in GitHub Desktop.
Save bgmort/6311947 to your computer and use it in GitHub Desktop.
/**
* converts like objects into a format which will serialize to a more compact JSON string
*/
function listToTable (list, cols){
var table = {};
for (var i = 0, item; item= list[i], i < list.length; i++){
for (var key in item){
if (item.hasOwnProperty(key)){
if (!table[key]) table[key] = [];
table[key][i] = item[key]
}
}
}
return {columns: table, length: i}
}
/**
* restores objects which were compacted by listToTable
*/
function tableToList (table){
var list = [];
var cols = [];
for (var key in table.columns){
if (table.columns.hasOwnProperty(key))
cols.push(key)
}
for (var i = 0; i < table.length; i++){
list[i] = {};
for (var c = 0, col; col = cols[c], c < cols.length; c++){
list[i][col] = table.columns[col][i];
}
}
return list
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment