Is there a way to download a Key: Value, type data array to a .CSV file?

Viewed 86

The below code which I need to use, with this Key: value data array does NOT work. Produces an error on this line:

+ data.map(e => e.join(",")).join("\n");
const downloadButton = document.getElementById("downloadButton")

let data = [{
    title: "",
    url: "",
    name: "",
    company: "",
    email: ""
   }]

let csvContent = "data:text/csv;charset=utf-8," 
    + data.map(e => e.join(",")).join("\n");

    var encodedUri = encodeURI(csvContent);
    window.open(encodedUri);

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); 

    downloadButton.addEventListener("click", function() {
        link.click()
    })

BUT this below code works, with this type data array

const downloadButton = document.getElementById("downloadButton")

let data = [
    ["rahul", "delhi", "accounts dept"],
    ["rajeev", "UP", "sales dept"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + data.map(e => e.join(",")).join("\n");

    var encodedUri = encodeURI(csvContent);
    window.open(encodedUri);

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); 

    downloadButton.addEventListener("click", function() {
        link.click()
    })

Only difference is the type of data array. First one has Key: value pair. How does one get this to download to a simple .CSV file?

1 Answers

To convert an array of objects to CSV, you can try this (the objects should have the same keys in the same order):

let data = [
  {
    title: "a",
    url: "b",
    name: "c",
    company: "d",
    email: "e"
  },
  {
    title: "f",
    url: "g",
    name: "h",
    company: "i",
    email: "j"
  },
];

const csvContent = "data:text/csv;charset=utf-8," +
  Object.keys(data[0]).join(",") + "\n" +
  data.map(entry => Object.values(entry).join(",")).join("\n");

console.log(csvContent);

Related