[Vuejs]-Save CSV from an array of objects in VueJs 3

0👍

Thanks to @traynor suggestion here is the full answer:

/* https://stackoverflow.com/a/58769574 */
arrayToCsv(data) {
    const array = [Object.keys(data[0])].concat(data)

    return array.map(it => {
        return Object.values(it).toString()
    }).join('\n');
},

/* https://stackoverflow.com/a/68146412 */
/* downloadBlob(csv, 'export.csv', 'text/csv;charset=utf-8;')*/
downloadBlob(content, filename, contentType) {
    // Create a blob
    var blob = new Blob([content], { type: contentType });
    var url = URL.createObjectURL(blob);

    // Create a link to download it
    var pom = document.createElement('a');
    pom.href = url;
    pom.setAttribute('download', filename);
    pom.click();
},

/* store.js
logs: [
        {
            time_stamp: new Date().toISOString(),
            message: " ============{ Logs }============",
            color: "white",
            name: 0,
        }
    ],
*/
saveLogs() { 
    const myLogs = this.arrayToCsv(store.logs);
    this.downloadBlob(myLogs, './gui_logs.csv', 'text/csv;charset=utf-8;');
    console.log("Logs has been saved");
}
👤Bilal

-1👍

You try to do it like it’s a 2D array, but it’s an array of JSON objects.
Like @traynor said, read this :

You can read this too :

Also consider using npm library like csv-writer (install with npm i csv-writer). You can find out an example here.

When downloading the file, I suggest you to set content-type to ‘text/csv’ and filename without ‘./’. After clicking a link you should remove it like that : pom.remove()

👤Alexis

Leave a comment