0

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

Ronnie
  • 205
  • 3
  • 12
  • Why rephrase an existing question. Just change the original question since it does not have any answers. Also please provide a [mcve] with input and expected output – mplungjan Aug 18 '19 at 09:11
  • There must be some errors in the console. For a click to work, your user must have clicked something – mplungjan Aug 18 '19 at 09:13
  • It wasn't attempting to download anything, so this is likely why. I had a button that had `onclick=createCSV()`, but I guess this doesn't doesn't count as the click? – Ronnie Aug 19 '19 at 14:11

1 Answers1

1

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();
}
Ronnie
  • 205
  • 3
  • 12