【发布时间】:2020-08-28 04:41:49
【问题描述】:
我正在尝试导入包含博客文章数组的 JSON 文件。 JSON 文件中包含的所有数据均已成功导入,但对象数组(边)除外
此代码是使用 JestJS 创建的单元测试的一部分,用于使用 Gatsby 构建站点。
当我尝试访问边数组时,我得到“TypeError: Cannot read property 'edges' of undefined”。
JS代码:
import data from "./__mocks__/blog.json";
console.log(data);
data.allMarkdownRemark.edges.forEach((post) => {
console.log(post);
})
Console.log(数据):
{ data: { allMarkdownRemark: { edges: [Array] } }
我的 JSON 文件被格式化为 JSON 对象,所以没有必要使用 JSON.parse() JSON 文件:
{
"data": {
"allMarkdownRemark": {
"edges": [
{
"node": {
"id": "c60d0972-1f4a-55ae-b762-c24795fae501",
"fields": {
"slug": "/a-tu-cerebro-no-le-gusta-la-innovacion/"
},
"frontmatter": {
"title": "A tu cerebro no le gusta la Innovación",
"templateKey": "blog-post",
"date": "September 16, 2017"
}
}
},
{
"node": {
"id": "1624f260-4c77-55d3-8297-4f0ad688f878",
"fields": {
"slug": "/la-mente-es-para-tener-ideas-no-para-almacenarlas/"
},
"frontmatter": {
"title": "La mente es para tener Ideas™, no para almacenarlas",
"templateKey": "blog-post",
"date": "August 26, 2017"
}
}
}
]
}
}
}
您知道如何从 JSON 文件中正确导入“edges”对象数组吗?
【问题讨论】:
标签: javascript arrays json jestjs gatsby