I have a .json array that contains objects, I fetch that array from the .json and save it to an array in my .js file.
[
{
"id": 1,
"name": "Burton Family Tree",
"price": 600,
"img": "url"
},
{
"id": 2,
"name": "Burton Mystery",
"price": 700,
"img": "url"
},
.
.
.
]
When I use the complete fetched array it works perfectly but when I want to use just one element of this array it shows an undefined error for the whole object itself and each attribute of it.
let products = [];
let productsURL = url;
async function loadProducts() {
try {
const response = await fetch(productsUrl);
const productsJSON = await response.json();
for (const item of productsJSON) {
products.push({
name: item.name,
price: item.price,
img: item.img,
});
}
} catch (error) {
console.log(error);
}
}
loadProducts();
console.log(products) -> works fine
console.log(products[0]) -> Uncaught Type Error: Cannot read properties of undefined
console.log(products[0].img) -> Uncaught Type Error: Cannot read properties of undefined (reading 'img')`