Created
June 7, 2015 01:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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