Skip to content

Instantly share code, notes, and snippets.

@muratgu
Created June 7, 2015 01:47
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 muratgu/e0b77f69674fdf1a4afd to your computer and use it in GitHub Desktop.
Save muratgu/e0b77f69674fdf1a4afd to your computer and use it in GitHub Desktop.
How to convert a Tabletop result (i.e. csv import) to a javascript object, using a target schema.
<script src="tabletop.js"></script>
<script type="text/javascript">
window.onload = function() {
init()
};
var public_spreadsheet_url = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html';
function init() {
Tabletop.init( {
key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true,
} )
}
var schema = {
'%Category': {
'%Name': {
'Healthiness': '%Healthiness',
},
},
};
function showInfo(data, tabletop) {
var food = convert(data, schema);
console.log(food);
}
function convert(data, schema) {
var traverse = function (row, schema, obj) {
for(j in schema){
var k = j
if (k[0] == '%') {
k = row[k.slice(1)]
}
if (typeof(schema[j]) === typeof({})) {
obj[k] = {};
traverse(row, schema[j], obj[k]);
} else {
var v = schema[j];
if (v[0] == '%') {
v = row[v.slice(1)];
}
obj[k] = v;
}
}
};
var instance = {}
for (i in data){
traverse(data[i], schema, instance);
}
return instance;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment