I’ve got a kind big dictionary as an API Response,
JavaScript
x
12
12
1
{totalHits: 379730, currentPage: 1, totalPages: 7595, pageList:
2
3
Array(10), foodSearchCriteria: {…}, …}
4
aggregations: {dataType: {…}, nutrients: {…}}
5
currentPage: 1
6
foodSearchCriteria: {pageNumber: 1, numberOfResultsPerPage: 50, pageSize: 50, requireAllWords: false}
7
foods: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
8
pageList: (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
9
totalHits: 379730
10
totalPages: 7595
11
__proto__: Object
12
How can I loop in a way to get each food from the foods array for every page (total: 7595)?
It may also be done with python-requests.
Advertisement
Answer
JavaScript
1
16
16
1
async function fetchFoodData() {
2
let foods = [];
3
let morePagesAvailable = true;
4
let currentPage = 0;
5
6
while(morePagesAvailable) {
7
currentPage++;
8
const response = await fetch(`http://yourapiurl.io/restlt?page=${currentPage}`)
9
let food = await response.json();
10
foods.push(food);
11
morePagesAvailable = currentPage < total_pages;
12
}
13
14
return foods;
15
}
16