Issues with looping through JSON data retrieved from a request

Today has been a battle with this code, as I tirelessly search for a solution. I've been using the fetch API to retrieve values and I can successfully iterate through the first JSON to grab the ID from the album section. Now, my goal is to use a loop to extract values from the second JSON and match them with the corresponding IDs from the first JSON. Specifically, I want to place the values with the same "albumId" from the photo section under each ID obtained from the first JSON.

Any help would be greatly appreciated.

async function getUsers() {
  let url = "https://jsonplaceholder.typicode.com/photos?albums";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function getPhotos() {
  let url2 = "https://jsonplaceholder.typicode.com/photos?photos";
  try {
    let res2 = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function renderUsers() {
  let albums = await getUsers();
  let html = "";
  albums.forEach((album) => {
    let htmlSegment = `<div class="user"><h2>${album.id}</h2></div>`;

    html += htmlSegment;
  });

  let container = document.querySelector(".container");
  container.innerHTML = html;
}

renderUsers();
<div class="container"></div>

Answer №1

The function renderUsers() calls both getUsers() and getPhotos() to retrieve user data and photo data. It then matches the photo album IDs to display the images in the HTML.

async function getUsers() {
  let url = "https://jsonplaceholder.typicode.com/photos?albums";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function getPhotos() {
  let url = "https://jsonplaceholder.typicode.com/photos?photos";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function renderUsers() {
  let [albums, photos] = await Promise.all([getUsers(), getPhotos()]);
  let html = "";
  albums.forEach((album) => {
    html += `<div class="user"><h2>${album.id}</h2>`;
    let albumPhotos = photos.filter(p => p.albumId == album.id);
    albumPhotos.forEach(photo => {
      html += `<img src="${photo.url}">`;
    });
    html += '</div>';
  });

  let container = document.querySelector(".container");
  container.innerHTML = html;
}

renderUsers();
<div class="container"> </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The useEffect hook fails to recognize changes in dependencies when using an object type obtained from useContext

Utilizing the useContext hook to handle theme management in my project. This is how the ThemeContext.js file appears: "use client"; import { createContext, useState } from "react"; let themes = { 1: { // Dark Theme Values ...

What is the best way to access a custom object in JavaScript that was created in a different function?

Currently working with JavaScript and jQuery technology. In one of my functions that runs on document ready, I am creating objects with different attributes. While I can easily access these object attributes within the same function, I'm facing diff ...

StealJS Module Repathing Techniques

There seems to be an issue with my setup, so I welcome all inquiries. I am utilizing an npm package called xrm-mock for a MS CRM mocking framework. Here is how I have configured it: steal.config({ meta: { "dependencyModule": { deps ...

How can we adjust the number of items based on the width of the viewport in Vue.js?

Imagine having a template that showcases a specific number of items, like this: <template> <div> <div v-for="item in items.slice(0, 10)" :key="item" /> </div> </template> How can I adjust the numbe ...

Working with extremely lengthy numbers exceeding 200 characters by utilizing char* arrays in the C programming language

I'm having trouble with an assignment that requires me to read a really long number from the console and then print it out using a char* array. After that, I need to add and subtract the numbers from two arrays. I think I can handle the adding and sub ...

Using Strapi to run basic raw SQL queries with MySQL

Trying to execute this query in my test but struggling with the correct syntax. return strapi.connections.default.raw(` delete from nurses; delete from users_permissions_user;`); }); Since this is not using PostgreSQL and MySQL ...

The error thrown states: "TypeError: Unable to access the property 'getFieldDecorator' of undefined in a React component."

Encountering this error: > TypeError: Cannot read property 'getFieldDecorator' of undefined > _class.render src/containers/RegisterTenant/register.js:81 78 | this.setState({ 'selectedFiles': files }); 79 | } 80 | > ...

unable to view icons from Summernote inline

I am currently using the Summernote editor, but I am experiencing some issues with the icons. Here is the image of the problem: https://i.sstatic.net/fRm0B.png My goal is to have all the icons aligned in a single line. Below is the code I am using: $(&a ...

The functionality of the code in a stack snippet may differ from that in a standalone HTML file

My code works perfectly on a stack snippet, but when I insert it into my server or an .html file, the refresh button shrinks! I have copied and pasted the code exactly as it is. Are there any specific snippet features that need to be added for it to work, ...

Calendars malfunctioning following the execution of npm run build

While utilizing the vue2-datepicker for a calendar, I encountered an issue during development. When clicking on the input box in my form, the calendar appeared as expected above the input. However, after running npm run build and loading up the resulting p ...

Can a 2D array be constructed with the row index arranged in descending order?

In my Python project, I am developing a game grid using a 2D array. The challenge I am facing is that when the grid is printed, I want the first column of each row to display a row label in reverse order (1 at the bottom and 5 at the top). Is there a way t ...

Tips for adding style to a group of SVG elements:

I currently have an array of .svg icons, each with unique properties that I need to customize: <svg width="24" height="24" viewBox="0 0 24 24"> ... </svg> import styled from 'styled-components'; import Github from 'assets/git ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Stopping HTTP redirection in Angular 2

Attempting to simulate user login using Angular2 Http. Let's describe the situation below. There is a PHP application where users can log in through http://sample.com/login.php URL (a form exists with username and password input, users must fill in ...

Unlocking the secrets of the Fibonacci function through mathematical equations

Looking for a better way to calculate the fibonacci function using a mathematical formula. I've tried the following formula without success: fib(n) = ((1 + 5^0.5) / 2)^n - ((1 - 5^0.5) / 2)^n / 5^0.5 const fib=(n)=>{ return ((1+(5**0.5))/2)* ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Example of Utilizing Google Places API

The Issue I've been struggling to make this google maps API example function correctly. Even after directly copying the code from Google's website, the example fails to display properly. For instance, the map doesn't show up, the search bar ...

ScrollReveal.js won't function as intended

https://i.stack.imgur.com/SOQEk.png Looking to utilize the popular ScrollReveal.js created by Julian Lloyd (ScrollReveal) Despite following instructions from various sources, the script is not producing the intended effect. Steps taken to make it work: ...

ReactAwesome Slider Autoplay Feature

I've been tinkering with a React Awesome Slider that you can find here: https://github.com/rcaferati/react-awesome-slider I've managed to implement it successfully, but I'm struggling to make it autoplay every 10 seconds. I assume I need to ...

Best practices for handling errors beyond network problems when using the fetch() function

I am facing a situation where the route of my fetch() call can result in two different responses, each requiring a different action. However, I have noticed that the catch() method only handles network errors as far as I know. Currently, my code looks lik ...