Parsing and displaying multiple entries from a JSON response in JavaScript

I’m working on a project that involves fetching data from a nutrition API. I’ve managed to get the JSON response, but I’m stuck on how to display each food item separately. Here’s a simplified version of what I’m dealing with:

const apiUrl = 'https://example-nutrition-api.com/search?q=beef';
const apiKey = 'my-secret-key';

fetch(apiUrl, {
  headers: { 'Authorization': `Bearer ${apiKey}` }
})
.then(response => response.json())
.then(data => {
  console.log(data);
  document.write(JSON.stringify(data));
})
.catch(error => console.error('Error:', error));

This code fetches the data and dumps it on the page, but it’s not very useful. The response contains multiple food items, each with properties like name, serving size, and nutritional info. How can I parse this data to display each food item in a more readable format? Maybe create a list or table with the important details for each item? Any suggestions would be appreciated!

I’ve dealt with a similar situation when working on a recipe app. Here’s what worked for me:

Instead of using document.write, you can create HTML elements dynamically. After parsing the JSON, loop through the data and create a div for each food item.

Something like this:

.then(data => {
  const container = document.getElementById('results');
  data.foods.forEach(food => {
    const foodDiv = document.createElement('div');
    foodDiv.innerHTML = `
      <h3>${food.name}</h3>
      <p>Serving: ${food.serving_size}</p>
      <p>Calories: ${food.calories}</p>
      <!-- Add more properties as needed -->
    `;
    container.appendChild(foodDiv);
  });
})

This approach gives you more control over the layout and styling. You can easily turn it into a table or list if you prefer. Remember to add error handling and maybe a loading indicator for better UX. Hope this helps!

hey, i’ve done similar stuff before. you could try using the reduce() method to create a table. something like:

.then(data => {
  const table = data.foods.reduce((acc, food) => 
    acc + `<tr><td>${food.name}</td><td>${food.calories}</td></tr>`, 
    '<table><tr><th>Food</th><th>Calories</th></tr>'
  ) + '</table>';
  document.body.innerHTML = table;
})

this creates a simple table with food names and calories. you can add more columns as needed.

Having worked with nutrition APIs before, I can suggest a more efficient approach. Instead of document.write, consider using template literals and the map() function to create a structured HTML output. Here’s an example:

.then(data => {
  const foodList = data.foods.map(food => `
    <div class='food-item'>
      <h4>${food.name}</h4>
      <p>Serving: ${food.serving_size} | Calories: ${food.calories}</p>
      <p>Protein: ${food.protein}g | Carbs: ${food.carbohydrates}g | Fat: ${food.fat}g</p>
    </div>
  `).join('');

  document.getElementById('results').innerHTML = foodList;
})

This method creates a cleaner, more readable output. You can easily style the ‘food-item’ class for better presentation. Remember to sanitize the data to prevent XSS attacks if you’re not sure about the API’s security measures.