I'm trying to fetch simple data from https://picsum.photos/v2/list
let data = [];
const f1_data = await fetch("https://picsum.photos/v2/list").then((res) =>
res.json()
);
data = f1_data;
console.log(data);
But I can't access data in the array, all I'm getting [object Object].
How, for example, I can access all authors or Theys ID, or any specific info in object?
CodePudding user response:
To answer the second part of your question, you can simply iterate over the array returned by the API like so:
for (const image of f1_data) {
console.log(image.author)
}
CodePudding user response:
The code below should work. You should await the json() function too. Also check this out for using await and then/catch.
let data = [];
const f1_data = await fetch("https://picsum.photos/v2/list");
const f1_data_json = await f1_data.json();
data = f1_data_json;
data.forEach((photo) => {console.log(photo.author)})
CodePudding user response:
You do have access to that data. The only problem is the way you are logging it. You can use JSON.stringify()
to convert your object to string.
let data = [];
const f1_data = await fetch("https://picsum.photos/v2/list").then((res) =>
res.json()
);
data = f1_data;
console.log(JSON.stringify(data));
Duplicate of How to print JSON data in console.log?