Guest User

Untitled

a guest
Oct 12th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. /**
  2. * Converts a value to a string appropriate for entry into a CSV table. E.g., a string value will be surrounded by quotes.
  3. * @param {string|number|object} theValue
  4. * @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted.
  5. */
  6. function toCsvValue(theValue, sDelimiter) {
  7. var t = typeof (theValue), output;
  8.  
  9. if (typeof (sDelimiter) === "undefined" || sDelimiter === null) {
  10. sDelimiter = '"';
  11. }
  12.  
  13. if (t === "undefined" || t === null) {
  14. output = "";
  15. } else if (t === "string") {
  16. output = sDelimiter + theValue + sDelimiter;
  17. } else {
  18. output = String(theValue);
  19. }
  20.  
  21. return output;
  22. }
  23.  
  24. /**
  25. * Converts an array of objects (with identical schemas) into a CSV table.
  26. * @param {Array} objArray An array of objects. Each object in the array must have the same property list.
  27. * @return {String} The CSV table.
  28. * @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted.
  29. * @param {string} cDelimiter The column delimiter. Defaults to a comma (,) if omitted.
  30. * @return {string} The CSV equivalent of objArray.
  31. */
  32. function toCsv(objArray, outputFile, sDelimiter, cDelimiter) {
  33. var i, l, names = [], name, value, obj, row, output = "", n, nl;
  34.  
  35. // Initialize default parameters.
  36. if (typeof (sDelimiter) === "undefined" || sDelimiter === null) {
  37. sDelimiter = '"';
  38. }
  39. if (typeof (cDelimiter) === "undefined" || cDelimiter === null) {
  40. cDelimiter = ",";
  41. }
  42.  
  43. for (i = 0, l = objArray.length; i < l; i += 1) {
  44. // Get the names of the properties.
  45. obj = objArray[i];
  46. row = "";
  47. if (i === 0) {
  48. // Loop through the names
  49. for (name in obj) {
  50. if (obj.hasOwnProperty(name)) {
  51. names.push(name);
  52. row += [sDelimiter, name, sDelimiter, cDelimiter].join("");
  53. }
  54. }
  55. row = row.substring(0, row.length - 1);
  56. output += row;
  57. }
  58.  
  59. output += "\n";
  60. row = "";
  61. for (n = 0, nl = names.length; n < nl; n += 1) {
  62. name = names[n];
  63. value = obj[name];
  64. if (n > 0) {
  65. row += ","
  66. }
  67. row += toCsvValue(value, '"');
  68. }
  69. output += row;
  70. }
  71.  
  72. return output;
  73. }
Add Comment
Please, Sign In to add comment