Ronnie
Ronnie

Reputation: 357

Exporting an array of arrays to CSV

I'm trying to loop through a multidimensional array to export it to CSV. I've tried to copy copy some of the guides online, and most seem to show similar solutions to How to export JavaScript array info to csv (on client side)? , however they all mention a const rows = where the array of information is entered. I've tried to modify this to loop through the arrays instead, but it's not prompting me to download the CSV, so I'm not sure if it's working. Can anyone advise what I'm doing wrong please.

function createCSV() {
    // loop the outer array
    for (var y = 0; y < properties.length; y++) {
        // get the size of the inner array
        var innerArrayLength = properties[y].length;
        // loop the inner array
        for (var z = 0; z < innerArrayLength; z++) {
            const rows = [
                [z]
            ];
            let csvContent = "data:text/csv;charset=utf-8,"
                + rows.map(e => e.join(",")).join("\n");
        }
    }

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

    link.click();
}

Note: this is a rephrasing of Export and append object to csv as I changed from using objects to multidimensional arrays, which fundamentally changed the question

Upvotes: 0

Views: 2877

Answers (1)

Ronnie
Ronnie

Reputation: 357

I was over complicating it. The below code has worked and I've created a button to trigger the function, rather than forcing a click.

function createCSV() {
    var csv = "";
    properties.forEach(function(row) {
        csv += row.join(',');
        csv += "\n";
    });

    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'properties.csv';
    hiddenElement.click();
}

Upvotes: 3

Related Questions