Home > OS >  loop problems in fetched json
loop problems in fetched json

Time:08-05

I'm still fighting with this code, actually i'm trying to find a solution, everywhere, i tried many times all the whole day. So, i have this code, i used the fetch API in order to get the values, i can iterate the first json because i need to get the id (from album json). now i would use the loop in order to get the values from the 2nd json in order to put under each id got from the first json the values with the same id from the second json so "albumId" from photo.

Thanks in advance

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 ><h2>${album.id}</h2></div>`;

    html  = htmlSegment;
  });

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

renderUsers();
<div ></div>

CodePudding user response:

Call both getUsers() and getPhotos() in renderUsers(). Then you can find the elements of photos with the matching albumId and add the images to 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 ><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 ></div>

  • Related