Search code examples
javascriptcsvexport-to-csv

javascript export object to csv as a table


I have a JS object (called df) that contains a number of arrays like so:

0: Array(2)
  0: "1405"
  1: "text string 1 #something"
1: Array(2)
  0: "1366"
  1: "text string 2 #hashtag"
603: Array(2)
  0: "92"
  1: "text string 603"

I want to export this into a csv file like so:

Views Title
1405 text string 1 #something
1366 text string 2 #hashtag
92 text string 603

I can export to csv with this:

const blob = new Blob([df], { type: "text/csv; charset=utf-8;" });
const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "export.csv");

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

but the output is messy:

A B C
1405 text string 1
#something
1366 text string 2 #hasthag

How can I clean this up in JS?

Edit: I have since found the cause of the issue being line breaks in the text field resulting in the remaining text being pushed to a new line.

The solution was to use regex to remove line breaks at the point of extracting the text:

innerText.replace(/(\r\n|\n|\r)/gm, " ")

Solution

  • You just need to convert the object to a CSV format string

    const autoDonwload = (obj) => {
      let result = `Views, Title`;
      for(const key in obj) {
        const [num, str] = obj[key];
        result += `\n`;
        result += `${num}, ${str}`;
      }
      // console.log(`result =\n`, result);
      const blob = new Blob([result], { type: "text/csv; charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.setAttribute("href", url);
      link.setAttribute("download", "export.csv");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };
    
    const obj = {
      0: ["1405", "text string 1 #something"],
      1: ["1366",  "text string 2 #hashtag"],
      603: ["92", "text string 603"],
    };
    
    autoDonwload(obj);
    
    

    demo

    enter image description here

    live demo

    https://codepen.io/xgqfrms/pen/xxmodaB

    update

    fix string contains , symbol issue

    const autoDonwload = (obj) => {
      // use `;` instead of `,` ✅
      let result = `Views; Title`;
      for(const key in obj) {
        const [num, str] = obj[key];
        result += `\n`;
        result += `${num}; ${str}`;
      }
      const blob = new Blob([result], { type: "text/csv; charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.setAttribute("href", url);
      link.setAttribute("download", "export.csv");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };
    
    const obj = {
      // string contains `,` symbol ❓
      0: ["1405", "text, string 1, #something"],
      1: ["1366",  "text string 2 #hashtag"],
      603: ["92", "text string 603"],
    };
    
    autoDonwload(obj);
    
    

    enter image description here

    refs

    https://en.wikipedia.org/wiki/Comma-separated_values