Looking for assistance (building on Christians solution) to understand why I can't pass a variable to a function and for it to work, when the same variable can be defined within the function (using the exact same output) and it works.
Here is my script.
<script>
    function UpdateGrid(AppGrid) {
        var json1 = JSON.stringify({ 'griddata': AppGrid });
        console.log(json1);
        var json2 = {
            "griddata": [{
                "id": "2",
                "row": "2",
                "col": "1",
                "sizex": "1",
                "sizey": "1"
            },
            {
                "id": "1",
                "row": "1",
                "col": "1",
                "sizex": "3",
                "sizey": "1"
                }
            ]
        }
        const items = json1.griddata
        console.log("1");
        const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
        console.log("2");
        const header = Object.keys(items[0])
        console.log("3");
        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)
    }
</script>
For reference, here is the output in the console of AppGrid
{"griddata":[{"id":"2","row":"2","col":"1","sizex":"1","sizey":"1"},{"id":"1","row":"1","col":"1","sizex":"3","sizey":"1"}]}
Some notes. var json1 is taking some JSON data and flattening it into a string. The output of this string, I have actually copied and pasted for json2 (below it). I have outputted json1 to the console, as well as a number of other checkpoints after each step, so i can follow along to see where it fails.
It is not getting to checkpoint 3, meaning it is getting caught on this line.
const header = Object.keys(items[0])
The error in the console is this.
Uncaught TypeError: Cannot read property '0' of undefined
If i change const items to json2.griddata then it works perfectly.
 
    