Export data collection to CSV with html, but it reorders the columns

I used this post example to export collection data to csv… Can’t figure out why the column structure of the download is not consistent with the collection schema though.

The file I download has completely reordered columns in no obvious meaningful way. The data collection exports from Wix dashboard in correct order. Does anybody know how I might structure the export to be same as the original collection? Must be happening when when going from JSON to CSV.

HTML Code:


<html>
<body>
    <p id="noticeBoard">Document Loading...</p>
    <!-- <button onclick='download_file("my_file.txt", dynamic_text())'>Download</button> -->
    <script>
    
    document.onreadystatechange = function () {
        if (document.readyState === "complete") {
            console.log("Document Loaded!");
            updateNoticeBoard("Document Loaded!");
        }
    }

    function updateNoticeBoard(message) {
        let messageArea = document.getElementById('noticeBoard');
        messageArea.innerHTML = message;
    }

    window.onmessage = (event) => {
        console.log("Message Received: "+(event.data.action ? event.data.action : "Bad Message"));
        if (event.data) {
            messageReceived(event.data);
        }
    };

    function sendMessageToPage(message) {
        window.parent.postMessage(message, "*");
    }

    function messageReceived(message) {
        if (message && message.action === 'data' && message.payload) {
            // Convert JSON to csv
            download_file("data.csv", csvFromJson(message.payload));
        } else if (message && message.payload) {
            updateNoticeBoard(message.payload);
        }
    }

    function download_file(name, contents, mime_type) {
        mime_type = mime_type || "text/plain";

        var blob = new Blob([contents], {type: mime_type});

        var dlink = document.createElement('a');
        dlink.download = name;
        dlink.href = window.URL.createObjectURL(blob);
        dlink.onclick = function(e) {
            // revokeObjectURL needs a delay to work properly
            var that = this;
            setTimeout(function() {
                window.URL.revokeObjectURL(that.href);
            }, 1500);
        };

        dlink.click();
        dlink.remove();
    }

    function csvFromJson(jsonData) {
        const items = JSON.parse(jsonData);
        const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
        const header = Object.keys(items[0])
        let csv = items.map(row => header.map(fieldName =>  JSON.stringify(row[fieldName], replacer)).join(','))
        csv.unshift(header.join(','))
        csv = csv.join('\r\n')

        console.log(csv)
        return csv
    }
    </script>
</body>
</html>