Convert Array to CSV

/**
* Converts a value to a string appropriate for entry into a CSV table. E.g., a string value will be surrounded by quotes.
* @param {string|number|object} theValue
* @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted.
*/
function toCsvValue(theValue, sDelimiter) {
try {
var t = typeof (theValue), output;

if (typeof (sDelimiter) === "undefined" || sDelimiter === null) {
sDelimiter = '"';
}
if (t === "undefined" || t === null) {
output = "";
} else if (t === "string") {
output = theValue;
} else {
output = theValue;
}
return output;
}catch(err){
log.debug('error@ csv conversion value',err)
}
}
/**
* Converts an array of objects (with identical schemas) into a CSV table.
* @param {Array} objArray An array of objects. Each object in the array must have the same property list.
* @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted.
* @param {string} cDelimiter The column delimiter. Defaults to a comma (,) if omitted.
* @return {string} The CSV equivalent of objArray.
*/
function toCsv(objArray, sDelimiter, cDelimiter) {
try {
var i, l, names = [], name, value, obj, row, output = "", n, nl;
for (i = 0, l = objArray.length; i < l; i += 1) {
obj = objArray[i];
row = "";
if (i === 0) {
for (name in obj) {
if (obj.hasOwnProperty(name)) {
names.push(name);
row += [name, cDelimiter].join("");
}
}
row = row.substring(0, row.length - 1);
}
if(i>=1) {
output += "\r\n";
}
row = "";
for (n = 0, nl = names.length; n < nl; n += 1) {
name = names[n];
value = obj[name];
if (n > 0) {
row += ","
}
row += toCsvValue(value, '"');
}
output += row;
}

return output;
}catch(error){
log.debug('error@csv conversion',error)
}
}

Leave a comment

Your email address will not be published. Required fields are marked *