Reputation: 63
I have a problem in returning the right data via javascript when fetching a file.json. The original has too many lines of code, so I will write a shorter example to make it clearer.
I have my data.json file that looks something like this:
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" },
]
},
}
My fetch works just fine, I can print out the data I want. For example, I don't want to get the objects that have "size" = "0" and that works. What does not work is the second condition: I want to get ONLY the objects that have some pictures (in other words, objects where pictures !== []) and I want the firsst pic in every object.
This is the part of my function that does that:
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
}
}
});
The error I get in the inspector is:
TypeError: Cannot read property 'source' of undefined at (index):94
!!! This code works if I hard code the id of the object instead of writing [key], like this:
img.src = data[01].picture[0].source // This is return the picture of the selected object
But of course, I need to get the right pic for each object. Any idea how to solve this? Thanks!
Upvotes: 0
Views: 51
Reputation: 3305
Check length of pictures like data[key].pictures.length > 0
instead of 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);
}
}
}
Upvotes: 1