data-exporter.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import Papa from 'papaparse';
  2. function generateJSON(keys, data) {
  3. const result = [];
  4. keys.forEach((key) => {
  5. for (let index = 0; index < data[key].length; index += 1) {
  6. const currData = data[key][index];
  7. if (typeof result[index] === 'undefined') {
  8. result.push({ [key]: currData });
  9. } else {
  10. result[index][key] = currData;
  11. }
  12. }
  13. });
  14. return result;
  15. }
  16. const files = {
  17. 'plain-text': {
  18. mime: 'text/plain',
  19. ext: '.txt',
  20. },
  21. json: {
  22. mime: 'application/json',
  23. ext: '.json',
  24. },
  25. csv: {
  26. mime: 'text/csv',
  27. ext: '.csv',
  28. },
  29. };
  30. export default function (data, { name, type }) {
  31. let result = data;
  32. if (type === 'csv' || type === 'json') {
  33. const jsonData = generateJSON(Object.keys(data), data);
  34. result =
  35. type === 'csv'
  36. ? `data:text/csv;charset=utf-8,${Papa.unparse(jsonData)}`
  37. : JSON.stringify(jsonData);
  38. } else if (type === 'plain-text') {
  39. result = Object.values(data).join(' ');
  40. }
  41. const { mime, ext } = files[type];
  42. const blob = new Blob([result], {
  43. type: mime,
  44. });
  45. const anchor = document.createElement('a');
  46. anchor.download = `${name || 'unnamed'}${ext}`;
  47. anchor.href = URL.createObjectURL(blob);
  48. anchor.dispatchEvent(new MouseEvent('click'));
  49. }