Created
March 26, 2012 03:30
-
-
Save syntagmatic/2202660 to your computer and use it in GitHub Desktop.
Export CSV with Javascript
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
// assumes variable data, which is a homogenous collection of objects | |
// get keys | |
var keys = _.keys(data[0]); | |
// convert to csv string | |
var csv = keys.join(","); | |
_(data).each(function(row) { | |
csv += "\n"; | |
csv += _(keys).map(function(k) { | |
return row[k]; | |
}).join(","); | |
}); | |
// trick browser into downloading file | |
var uriContent = "data:application/octet-stream," + encodeURIComponent(csv); | |
var myWindow = window.open(uriContent, "Nutrient CSV"); | |
myWindow.focus(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, this does not seem RFC840 compliant and could cause errors. Consider for example if one of the keys has a newline in it.