Last active
May 14, 2017 10:21
-
-
Save kjantzer/7679301 to your computer and use it in GitHub Desktop.
Backbone.Collection.saveToCSV() — adds ability to save all of the collections models as a CSV file. NOTE: only tested on Chrome; may not work on all browsers, but would work well for packaged Chrome apps.
This file contains hidden or 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
/* | |
Save To CSV 0.0.2 | |
@author Kevin Jantzer, Blackstone Audio | |
@since 2015-01-16 | |
intial code from http://stackoverflow.com/a/14966131/484780 | |
TODO | |
- needs improved (objects as values) | |
- consolidate opts and `downloadName` | |
*/ | |
_.mixin({ | |
saveToCSV: function(rawData, opts){ | |
opts = _.extend({ | |
downloadName: '', | |
timestamp: true, | |
title: '', | |
description: '', | |
prettyHeader: true | |
}, opts) | |
var downloadName = (opts.downloadName ? opts.downloadName : 'CSV data') +(opts.timestamp?' - '+(new XDate()).toString('yyyy-MM-dd hhmmss'):''); | |
if( !rawData || rawData.length == 0 ) | |
return console.log('No data to export'); | |
var firstRow = rawData[0] instanceof Backbone.Model ? rawData[0].csvData() : rawData[0]; | |
var header = _.map(_.keys(firstRow), function(val){ return opts.prettyHeader ? _.keyToText(val) : val; }) | |
var rows = _.map(rawData, function(m){ | |
return _.values( m instanceof Backbone.Model ? m.csvData() : m ) | |
}) | |
var data = [header].concat(rows); | |
if( opts.title || opts.description ) | |
data.unshift([]); | |
if( opts.description ) | |
data.unshift([opts.description]); | |
if( opts.title ) | |
data.unshift([opts.title]); | |
data = _.map(data, function(row){ | |
return _.map(row, function(val, key){ | |
if( _.isString(val) && val.match(/,|\n|"/) ){ | |
val = '"'+val+'"'; | |
} | |
else if( _.isArray(val) ) | |
val = '"'+val.toString()+'"'; | |
return val; | |
}) | |
}) | |
var csvContent = ""; | |
data.forEach(function(infoArray, index){ | |
dataString = infoArray.join(","); | |
csvContent += index < data.length ? dataString+ "\n" : dataString; | |
}); | |
blob = new Blob([csvContent], {type:'text/csv'}); | |
var csvUrl = window.URL.createObjectURL(blob); | |
var link = document.createElement("a"); | |
link.setAttribute("href", csvUrl); | |
link.setAttribute("download", downloadName+".csv"); | |
link.click(); | |
} | |
}); | |
_.extend(Backbone.Collection.prototype, { | |
saveToCSV: function(downloadName, opts){ | |
var data = this.map(function(m){ return m.csvData() }) | |
if( data.length > 0 && _.isArray(data[0]) ) | |
data = _.flatten(data); | |
_.saveToCSV(data, _.extend({downloadName: downloadName}, opts)) | |
} | |
}); | |
_.extend(Backbone.Model.prototype, { | |
csvData: function(str){ | |
return this.templateData ? this.templateData() : this.toJSON(); | |
}, | |
saveToCSV: function(opts){ | |
_.saveToCSV([this.csvData()], opts) | |
} | |
}) |
@pgilad - this is fixed now. Also added csvData
method to Backbone.Model that can be overridden to return a formatted or partially omitted dataset.
Example: return _.omit(this.toJSON(), 'id')
Where is _.keyToText
coming from? I don't see it in the underscore docs
@avoliva – Oops, _.keyToText
was a custom mixin I made. It uses humanize
and titlize
from Underscore String and a few custom string replacements for capitalizing things like Isbn
to ISBN
keyToText: function(text){
text = text || '';
text = _.humanize(text) // convert underscore and hypen to spaces
text = text.replace(/ id$/, ' ID') // capitialize ID
text = text.replace(/isbn/g, 'ISBN') // capitialize ISBN
text = text.replace(/www/g, 'WWW') // capitialize ISBN
text = text.replace(/drm/g, 'DRM') // capitialize DRM
text = text.replace(/amt/g, 'Amount') // convert amt to Amount
text = text.replace(/nyt/g, 'NYT')
text = text.replace(/html/g, 'HTML')
text = text.replace(/poid/g, 'POID')
text = _.titleize(text);
return text;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will break with quotes or
,
in strings