在获取file.json时,通过javascript返回正确的数据有问题。原来的代码行太多了,因此我将编写一个简短的示例,以使其更清晰。
我的data.json文件如下所示:
data.json
{
"01": {
"id" : "01",
"title" : "example1",
"size" : "100",
"pictures" : []
},
"02": {
"id" : "02",
"title" : "example2",
"size" : "0",
"pictures" : []
},
"03": {
"id" : "03",
"title" : "example3",
"size" : "300",
"pictures" : [
{ "pic_name1" : "example_pic1", "source" : "http://example.pic/1234" },
{ "pic_name2" : "example_pic2", "source" : "http://example.pic/4321" },
]
},
}我的抓取功能很好,我可以打印出我想要的数据。例如,我不希望获得具有"size“= "0”且工作正常的对象。不起作用的是第二个条件:我只想得到有一些图片的对象(换句话说,是图片的对象!== []),我想要每个对象的第一张图片。
这是我职能的一部分:
main.js
getData().then(data => {
for (const key in data) {
if (data.hasOwnProperty(key)) {
if (data[key].size !== "0" && data[key].pictures !== [] ) {
div.innerText = data[key].size; // This prints the right data in DOM
img.src = data[key].pictures[0].source // This gives an error
}
}
});我从检验员那里得到的错误是:
TypeError:无法读取(索引):94处未定义的属性“源”
!!!如果我硬编码对象的id而不是写入键,则此代码可以工作,如下所示:
img.src = data[01].picture[0].source // This is return the picture of the selected object但当然,我需要为每个物体得到正确的图片。知道怎么解决这个问题吗?谢谢!
发布于 2020-11-20 12:21:33
检查像data[key].pictures.length > 0这样的图片的长度而不是data[key].pictures !== []
let data = {
"01": {
"id" : "01",
"title" : "example1",
"size" : "100",
"pictures" : []
},
"02": {
"id" : "02",
"title" : "example2",
"size" : "0",
"pictures" : []
},
"03": {
"id" : "03",
"title" : "example3",
"size" : "300",
"pictures" : [
{ "pic_name1" : "example_pic1", "source" : "http://example.pic/1234" },
{ "pic_name2" : "example_pic2", "source" : "http://example.pic/4321" },
]
},
}
for (const key in data) {
if (data.hasOwnProperty(key)) {
if (data[key].size !== "0" && data[key].pictures.length>0){
console.log(data[key].size);
console.log(data[key].pictures[0].source);
}
}
}
https://stackoverflow.com/questions/64929257
复制相似问题