Skip to content
Advertisement

Looping through dictionary in API response

I’ve got a kind big dictionary as an API Response,

{totalHits: 379730, currentPage: 1, totalPages: 7595, pageList: 

Array(10), foodSearchCriteria: {…}, …}
aggregations: {dataType: {…}, nutrients: {…}}
currentPage: 1
foodSearchCriteria: {pageNumber: 1, numberOfResultsPerPage: 50, pageSize: 50, requireAllWords: false}
foods: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
pageList: (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalHits: 379730
totalPages: 7595
__proto__: Object

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

async function fetchFoodData() {
  let foods = [];
  let morePagesAvailable = true;
  let currentPage = 0;

  while(morePagesAvailable) {
    currentPage++;
    const response = await fetch(`http://yourapiurl.io/restlt?page=${currentPage}`)
    let food = await response.json();
    foods.push(food);
    morePagesAvailable = currentPage < total_pages;
  }

  return foods;
}
Advertisement