skip to Main Content

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?

2

Answers


  1. You can try converting the array to CSV format

    const arrayToCsv = (data) => data.map((row) => row.join(",")).join("n");
    

    Use this while exporting

    const blob = new Blob([arrayToCsv(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);
    
    Login or Signup to reply.
  2. 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

    refs

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search