Guest User

Untitled

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