0

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.

rrk
  • 14,861
  • 4
  • 25
  • 41
Stephen85
  • 226
  • 1
  • 11
  • 1
    `JSON.stringify` produces a string, `json1.griddata` would be `undefined` hence the error – Anurag Srivastava Apr 18 '20 at 23:27
  • 1
    Oh, sometimes someone else prodding you with what should have been obvious has done the trick. I have fixed my code and it's working now. Thanks Anurag. I felt like i was just becoming 'snowblind' to the problem and trying to tack on extra code, when i needed to take a few things away. – Stephen85 Apr 18 '20 at 23:31

1 Answers1

0

@Anurag pointed out an issue from line 1 of my function, and the solution for me was to remove JSON.stringify. I also had this format being passed to this function, and removed it there also.

The declaration that works is simply just:

var json1 = AppGrid;
Stephen85
  • 226
  • 1
  • 11