0

I have a problem with a javascript (i'm a noob) so i can't figure out a solution. Actually i have a json file, i can achieve to get the results i need, but are not grouped, and i can 't find a way for group them. What i would achieve is to have all the albums of userid1 in a group and so on. I tried using Groupby, but seems not working. May can you help me? That's the code.

Thanks for help

EDIT: There's a second Json called photos... so i tried to merge them in order to have just one json file...but i think i miss something because seems to not work

async function getAlbums() {
  let url = 'https://jsonplaceholder.typicode.com/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';
  try {
    let res1 = await fetch(url);
    return await res1.json();
  } catch (error) {
    console.log(error);
  }
}

async function renderAlbums() {
  let albums = await getAlbums();

  let html = '';
  albums.forEach(albums => {
    let htmlSegment = `<div class="albums">
                            <h2>ALBUM MADE BY USER
                            ${albums.userId} </h2>
                            <h2>ALBUM NAME: ${albums.title}</h2>
                            <div class="photos">
                             
                      </div>`;

    html += htmlSegment;
  });

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

renderAlbums();
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – IT goldman Aug 03 '22 at 21:36
  • It's exactly what i tried to do, the same example too, looks like not working, because then in the console log i can't see anything. – Sasha 1981 Aug 03 '22 at 21:40

3 Answers3

0

Let's group the albums see if it helps. I didn't quite understand why you want to group.

var albums = [{"userId":1,"id":7,"title":"quibusdam autem aliquid et et quia"},{"userId":1,"id":8,"title":"qui fuga est a eum"},{"userId":1,"id":9,"title":"saepe unde necessitatibus rem"},{"userId":1,"id":10,"title":"distinctio laborum qui"},{"userId":2,"id":11,"title":"quam nostrum impedit mollitia quod et dolor"},{"userId":2,"id":12,"title":"consequatur autem doloribus natus consectetur"},{"userId":2,"id":13,"title":"ab rerum non rerum consequatur ut ea unde"},{"userId":2,"id":14,"title":"ducimus molestias eos animi atque nihil"},{"userId":2,"id":15,"title":"ut pariatur rerum ipsum natus repellendus praesentium"},{"userId":2,"id":16,"title":"voluptatem aut maxime inventore autem magnam atque repellat"},{"userId":2,"id":17,"title":"aut minima voluptatem ut velit"},{"userId":2,"id":18,"title":"nesciunt quia et doloremque"},{"userId":2,"id":19,"title":"velit pariatur quaerat similique libero omnis quia"},{"userId":2,"id":20,"title":"voluptas rerum iure ut enim"},{"userId":3,"id":21,"title":"repudiandae voluptatem optio est consequatur rem in temporibus et"},{"userId":3,"id":22,"title":"et rem non provident vel ut"},{"userId":3,"id":23,"title":"incidunt quisquam hic adipisci sequi"},{"userId":3,"id":24,"title":"dolores ut et facere placeat"},{"userId":3,"id":25,"title":"vero maxime id possimus sunt neque et consequatur"},{"userId":3,"id":26,"title":"quibusdam saepe ipsa vel harum"},{"userId":3,"id":27,"title":"id non nostrum expedita"},{"userId":3,"id":28,"title":"omnis neque exercitationem sed dolor atque maxime aut cum"}];

var grouped = albums.reduce(function(agg, item) {
  agg[item.userId] = agg[item.userId] || []
  agg[item.userId].push (item)
  return agg;
}, {})

console.log(grouped)
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • I see that now groups, but i should achieve it by calling the json with that API and not writing the json itself in a variable. I want to group because then the other part is to get the elements from the photos.json, and group them too by the common element. So at the end i should achieve that i have, UserId1 made this album and in this album there are these pictures. – Sasha 1981 Aug 03 '22 at 21:55
  • Ok so like I grouped `albums`, you group the `photos` to another object. Now it should be easy `forEach` album (of `forEach` user) to attach its photos. – IT goldman Aug 03 '22 at 22:04
  • Yes, but the problem is that i can't write var albums how you did, i have to fetch it, that's also a problem, if i write it works perfectly, but i must fetch and then use it, but you've been already a lot helpful, thanks. – Sasha 1981 Aug 03 '22 at 22:06
  • You can fetch multiple jsons either one after another or in parallel. Then you should start manipulating the results https://stackoverflow.com/questions/46241827/fetch-api-requesting-multiple-get-requests – IT goldman Aug 05 '22 at 09:28
0

Check this one - Group Javascript array of objects by ID

In your case, try using reduce(), do it like that:

 // Don't put this, I've put it only for better understanding  
// var albums = [{"userId":1,"id":7,"title":"quibusdam autem aliquid et et quia"},{"userId":1,"id":8,"title":"qui fuga est a eum"},{"userId":1,"id":9,"title":"saepe unde necessitatibus rem"},{"userId":1,"id":10,"title":"distinctio laborum qui"},{"userId":2,"id":11,"title":"quam nostrum impedit mollitia quod et dolor"},{"userId":2,"id":12,"title":"consequatur autem doloribus natus consectetur"},{"userId":2,"id":13,"title":"ab rerum non rerum consequatur ut ea unde"},{"userId":2,"id":14,"title":"ducimus molestias eos animi atque nihil"},{"userId":2,"id":15,"title":"ut pariatur rerum ipsum natus repellendus praesentium"},{"userId":2,"id":16,"title":"voluptatem aut maxime inventore autem magnam atque repellat"},{"userId":2,"id":17,"title":"aut minima voluptatem ut velit"},{"userId":2,"id":18,"title":"nesciunt quia et doloremque"},{"userId":2,"id":19,"title":"velit pariatur quaerat similique libero omnis quia"},{"userId":2,"id":20,"title":"voluptas rerum iure ut enim"},{"userId":3,"id":21,"title":"repudiandae voluptatem optio est consequatur rem in temporibus et"},{"userId":3,"id":22,"title":"et rem non provident vel ut"},{"userId":3,"id":23,"title":"incidunt quisquam hic adipisci sequi"},{"userId":3,"id":24,"title":"dolores ut et facere placeat"},{"userId":3,"id":25,"title":"vero maxime id possimus sunt neque et consequatur"},{"userId":3,"id":26,"title":"quibusdam saepe ipsa vel harum"},{"userId":3,"id":27,"title":"id non nostrum expedita"},{"userId":3,"id":28,"title":"omnis neque exercitationem sed dolor atque maxime aut cum"}];


async function renderAlbums() {
  let albums = await getAlbums();
var o = {}

  var result = albums.reduce(function (r, el) {
  var e = el.id.slice(0, 2);
  if (!o[e]) {
    o[e] = {
      userId: el.userId,
      id: el.id,
      title: []
    }
    r.push(o[e]);
  }
  o[e].title.push(el.title);
  return r;
}, [])
  }
    let htmlSegment = `<div class="albums">
                            <h2>ALBUM MADE BY USER
                            ${result.userId} </h2>
                            <h2>ALBUM NAME: ${result.title}</h2>
                            <div class="photos">
                             
                      </div>`;
                      
  });

  let container = document.querySelector('.container');
  container.innerHTML = htmlSegment;
}

renderAlbums();

Let me know if that solves your problem :)

Vladimir B.
  • 304
  • 2
  • 16
  • I tried but unfortunately doen't work :-( – Sasha 1981 Aug 03 '22 at 22:00
  • I tried, but it's not woring, besides if i write the json itself, so in the way you commented, it works....maybe should i store in a var first? but i thought that "res" was already the var containing the json – Sasha 1981 Aug 03 '22 at 22:04
  • The problem remains that you still need to merge the two json responses into one, right? Please review this one and try assigning the different json responses like the code in the answer - https://stackoverflow.com/questions/63639367/how-to-combine-two-json-response-and-send-it-as-a-whole – Vladimir B. Aug 03 '22 at 22:17
0

i made this solution for getAlbums(), you can make the same for the other function i guess.

async function getAlbums() {
  let url = 'https://jsonplaceholder.typicode.com/albums';
  try {
    let res = await fetch(url);
    let resJson = await res.json();

let grouped = resJson.reduce((grp, album)=>{
    grp[album.userId] = grp[album.userId] || []
    grp[album.userId].push(album)
    return grp
})
console.log(grouped)

  } catch (error) {
    console.log(error);
  }
}
Samoox
  • 176
  • 1
  • 2
  • 9