Files
P42_UI/app/helpers/translator.js
T
2025-08-27 07:03:09 +00:00

78 lines
2.7 KiB
JavaScript

if(!app.helpers) app.helpers = {}
/**
* Helper for data transformation.
* @class Translator
* @category MyEic
* @subcategory Helpers
*/
app.helpers.translator = {
toCSV(collection, options /* keys=null, withHeader=true, quoteChar = '"', delimiter = ';', downloadName=null */) {
let defaultOptions = {
headers: [],
delimiter: ',',
quoteCharacter: '"',
filename: 'data'
}
options = {...defaultOptions, ...options}
/**/
const _download = function(data, filename) {
const blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF]), data], { type: 'text/csv; charset=utf-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', filename + '.csv');
a.click();
}
if(!options.keys) { // take min. common set of keys in collection (take 1st then successively intersect to itself)
let ids = Object.keys(collection);
options.keys = Object.keys(collection[ids[0]]);
for(let id of ids) {
options.keys = options.keys.filter(x => (collection[id].hasOwnProperty(x)))
}
}
let csv='';
let row=[];
if(options.headers && options.headers.length > 0){
for(let key of options.headers) {
row.push(options.quoteCharacter + key + options.quoteCharacter);
}
csv += row.join(options.delimiter)+'\n';
} else if(Array.isArray(options.headers)) {
for(let title of options.headers){
row.push(options.quoteCharacter + title + options.quoteCharacter);
}
csv += row.join(options.delimiter)+'\n';
}
for(let id in collection){
row = [];
for(let key of options.keys){
let item = ''
if(typeof(key)=='string'){ // normal column
item = collection[id]
for(let k of key.split('.')) { // Allow for sub-objects with dotted keys notation
if(!item) break
item = item[k]
}
} else if(typeof(key)=='function') { // computed column
item = key(collection[id])
} else console.warn('CSV: Bad column: ',key)
row.push(options.quoteCharacter + item + options.quoteCharacter);
}
csv += row.join(options.delimiter)+'\n';
}
if(options.filename) _download(csv, options.filename);
return(csv);
},
fromCSV() {
}
}