Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => console.log(data));

I fetch a JSON, but I do not know how to use data object out of the arrow function?

I have got: data is not defined.

What I have tried:

JavaScript
fetch('https://jsonplaceholder.typicode.com/posts')
    .then((response) => response.json())
    .then((data) => console.log(data));

const titles = data.title;

for (const title of titles) {
    console.log(title);
}
Posted
Updated 1-Nov-22 0:02am
v2
Comments
Member 15627495 31-Oct-22 15:28pm    
console.table(data);

by for each you access only the first depth of the data array.

It's json, it's n-dimensions array so often. maybe the datas are at depth 2 / or 3
{{{data1:value,data2:value2},,{and so and so}}}; is different from 1 dimension array : {data1,data2}


arrow function are 'lambda expressions'
folza 31-Oct-22 15:38pm    
Could You show an code example to get for example the titles with for loop?
Member 15627495 31-Oct-22 15:41pm    
I can't guess the 'datas' array structure by myself ... It's now your turn to complete your request.
what do you have in console.table(data) ? please
folza 31-Oct-22 15:48pm    
I have a table with correct values
folza 31-Oct-22 15:56pm    
Copy the link!

1 solution

When you use promises (ie. fetch()) you can only access the data within the then() function. The data produced from that API is a JSON array of objects, so you can iterate over the values as so:

JavaScript
fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => {

    // You can only access the data from the response in here

    for (const item of data) {
      console.log(item.title);
    }
  });

Or you can use a more modern async/await approach:

JavaScript
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = response.json();

for (const item of data) {
  console.log(item.title);
}
 
Share this answer
 
v2
Comments
Richard Deeming 1-Nov-22 6:36am    
Might be worth noting that you can't use a top-level await[^] outside of a module[^]. :)
Chris Copeland 1-Nov-22 9:13am    
I did not know that, thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900