【问题标题】:Object.keys(items[0]) - Cannot read property '0' of undefinedObject.keys(items[0]) - 无法读取未定义的属性“0”
【发布时间】:2020-08-01 11:43:29
【问题描述】:

寻求帮助 (building on Christians solution) 以了解为什么我不能将变量传递给函数并使其工作,当可以在函数中定义相同的变量(使用完全相同的输出)并且它可以工作时.

这是我的脚本。

<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>

作为参考,这里是 AppGrid 控制台中的输出

{"griddata":[{"id":"2","row":"2","col":"1","sizex":"1","sizey":"1"},{"id":"1","row":"1","col":"1","sizex":"3","sizey":"1"}]}

一些注意事项。 var json1 正在获取一些 JSON 数据并将其展平为字符串。这个字符串的输出,其实我已经为json2复制粘贴了(在它下面)。我已经将 json1 以及每个步骤之后的许多其他检查点输出到控制台,因此我可以继续查看它失败的地方。

它没有到达检查点 3,这意味着它被捕获在这条线上。

const header = Object.keys(items[0])

控制台中的错误是这样的。

未捕获的类型错误:无法读取未定义的属性“0”

如果我将 const items 更改为 json2.griddata,那么它可以完美运行。

【问题讨论】:

  • JSON.stringify 产生一个字符串,json1.griddata 将是 undefined 因此错误
  • 哦,有时其他人用本应显而易见的东西来刺激你已经成功了。我已经修复了我的代码,它现在可以工作了。谢谢阿努拉格。当我需要删除一些东西时,我觉得我只是对问题变得“雪盲”并试图添加额外的代码。

标签: jquery asp.net json


【解决方案1】:

@Anurag 从我的函数的第 1 行指出了一个问题,我的解决方案是删除 JSON.stringify。我也将这种格式传递给了这个函数,并在那里删除了它。

有效的声明只是:

var json1 = AppGrid;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多