0

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Andrew
  • 17
  • 6
  • 1
    Why don't you use the data within another `.then()`, like it is done in these [examples](https://developer.mozilla.org/en-US/docs/Web/API/fetch#examples)? – Geshode Aug 24 '22 at 07:48
  • 1
    The OP simply needs to e.g. [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#using_map_to_reformat_objects_in_an_array) the `f1_data` / `data` array(s) – Peter Seliger Aug 24 '22 at 08:00

3 Answers3

1

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)
}
kil
  • 160
  • 1
  • 8
0

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)})
mscandan
  • 37
  • 1
  • 4
-1

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?

marekvospel
  • 412
  • 4
  • 9